C++ Timers
Published:
The following code illustrates the usage of various APIs to time execution in C++ code. Some of these are applicable in C as well.
>
#include <chrono>
#include <cstdint>
#include <math.h> /* sqrt */
#include <stdio.h> /* printf */
#include <sys/time.h>
#include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */
using namespace std::chrono;
// THe function to be timed.
int frequency_of_primes(int n) {
int i, j;
int freq = n - 1;
for (i = 2; i <= n; ++i)
for (j = sqrt(i); j > 1; --j)
if (i % j == 0) {
--freq;
break;
}
return freq;
}
int main() {
clock_t start1, end1;
time_t start2, end2;
timeval start3, end3;
std::chrono::time_point<std::chrono::system_clock> start4, end4;
std::chrono::high_resolution_clock::time_point start5, end5;
/* Collect the start times using different methods. */
// Method 1
start1 = clock();
// Method 2
time(&start2);
// Method 3
gettimeofday(&start3, NULL);
// Method 4
start4 = std::chrono::system_clock::now();
// Method 5
start5 = std::chrono::high_resolution_clock::now();
// The computaton to be timed.
printf("Calculating...\n");
int f = frequency_of_primes(999999);
printf("The number of primes lower than 100,000 is: %d\n\n", f);
/* Collect the end times using different methods. */
// Method 1
end1 = clock();
// Method 2
time(&end2);
// Method 3
gettimeofday(&end3, NULL);
// Method 4
end4 = std::chrono::system_clock::now();
// Method 5
end5 = std::chrono::high_resolution_clock::now();
/* Compute elapsed times using different methods. */
// Method 1
long int elapsed_seconds1 = end1 - start1;
// Method 2
double elapsed_seconds2 = difftime(end2, start2);
// Method 3
double elapsed_seconds3 = (double(end3.tv_sec - start3.tv_sec)) * 1000000.00 +
double(end3.tv_usec - start3.tv_usec);
// Method 4
std::chrono::duration<double> elapsed_seconds4 = end4 - start4;
// Method 5
std::chrono::duration<double> elapsed_seconds5 = (end5 - start5);
double elapsed_seconds6 =
double(duration_cast<nanoseconds>(end5 - start5).count());
/* Display the elapsed times */
printf("Clock: %ld clicks (%f us).\n", elapsed_seconds1,
(double(elapsed_seconds1)) * 1000000.00 / CLOCKS_PER_SEC);
printf("Time: %f us).\n", elapsed_seconds2 * 1000000.00);
printf("gettimeofday: %f us).\n", elapsed_seconds3);
printf("chrono::system_clock %f us).\n",
elapsed_seconds4.count() * 1000000.00);
printf("chrono::high_resolution_clock %f us).\n",
elapsed_seconds5.count() * 1000000.00);
printf("chrono::high_resolution_clock %f us).\n", elapsed_seconds6);
return 0;
}