Created
September 10, 2017 01:24
-
-
Save sdasgup3/32f050305f9e6a08b0eaab68810e3f1a to your computer and use it in GitHub Desktop.
Comparison of various c++ timers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* clock example: frequency of primes */ | |
#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; | |
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; | |
int f; | |
start1 = clock(); | |
time(&start2); | |
gettimeofday(&start3, NULL); | |
double t1 = start3.tv_usec; | |
start4 = std::chrono::system_clock::now(); | |
start5 = std::chrono::high_resolution_clock::now(); | |
printf("Calculating...\n"); | |
f = frequency_of_primes(999999); | |
printf("The number of primes lower than 100,000 is: %d\n\n", f); | |
end1 = clock(); | |
time(&end2); | |
gettimeofday(&end3, NULL); | |
end4 = std::chrono::system_clock::now(); | |
end5 = std::chrono::high_resolution_clock::now(); | |
long int elapsed_seconds1 = end1 - start1; | |
double elapsed_seconds2 = difftime(end2, start2); | |
double elapsed_seconds3 = (double(end3.tv_sec - start3.tv_sec)) * 1000000.00 + | |
double(end3.tv_usec - start3.tv_usec); | |
std::chrono::duration<double> elapsed_seconds4 = end4 - start4; | |
std::chrono::duration<double> elapsed_seconds5 = (end5 - start5); | |
double elapsed_seconds6 = | |
double(duration_cast<nanoseconds>(end5 - start5).count()); | |
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment