Last active
September 14, 2015 07:20
-
-
Save skaslev/1b4b0e854d712be5ac3f to your computer and use it in GitHub Desktop.
Nanosecond precision timer
This file contains hidden or 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
| #include <stdint.h> | |
| #include <stdio.h> | |
| #include <time.h> | |
| namespace { | |
| const int64_t SEC = 1; | |
| const int64_t MILI = 1000; // 10^3 | |
| const int64_t MICRO = 1000 * 1000; // 10^6 | |
| const int64_t NANO = 1000 * 1000 * 1000; // 10^9 | |
| class Timer { | |
| public: | |
| void tick() { | |
| clock_gettime(CLOCK_MONOTONIC, &t0_); | |
| } | |
| void tock() { | |
| clock_gettime(CLOCK_MONOTONIC, &t1_); | |
| } | |
| int64_t nano() const { | |
| return (t1_.tv_sec - t0_.tv_sec) * NANO + (t1_.tv_nsec - t0_.tv_nsec); | |
| } | |
| double micro() const { | |
| return MICRO * sec(); | |
| } | |
| double mili() const { | |
| return MILI * sec(); | |
| } | |
| double sec() const { | |
| return double(nano()) / NANO; | |
| } | |
| private: | |
| timespec t0_; | |
| timespec t1_; | |
| }; | |
| } // namespace | |
| int main() { | |
| const double N_SEC = 2; // [sec] | |
| // 3.4GHz CPU means: | |
| // 1 [sec] = 3.4e9 [ops] | |
| const double OPS_PER_SEC = 3.4e9; // [ops/sec] for a 3.4 GHz CPU | |
| // 1 [iter] = 3 [ops] | |
| const double OPS_PER_ITER = 3; // [ops/iter] | |
| // => 1 [sec] = 3.4e9 / 3 [iter] | |
| const double N_ITER = N_SEC * OPS_PER_SEC / OPS_PER_ITER; // [iter] | |
| Timer timer; | |
| timer.tick(); | |
| double sum = 0; | |
| for (double i = 1; i <= N_ITER; ++i) { | |
| sum += i; | |
| } | |
| timer.tock(); | |
| printf("%ld [ns]\n", timer.nano()); | |
| printf("measured %f [s]\n", timer.sec()); | |
| printf("expected %f [s] for %f GHz CPU\n", N_SEC, OPS_PER_SEC / 1e9); | |
| printf("estimated CPU speed %f GHz\n", OPS_PER_ITER * N_ITER / timer.sec() / 1e9); | |
| printf("sum: %f\n", sum); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment