Skip to content

Instantly share code, notes, and snippets.

@pervognsen
Last active August 28, 2023 10:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save pervognsen/496d659251ad2af200dde4c773bd565f to your computer and use it in GitHub Desktop.
Save pervognsen/496d659251ad2af200dde4c773bd565f to your computer and use it in GitHub Desktop.
#if _WIN32
// measure the time in seconds to run f(). doubles will retain nanosecond precision.
template<typename F>
double timeit(F f) {
LARGE_INTEGER freq;
QueryPerformanceFrequency(&freq);
LARGE_INTEGER start;
QueryPerformanceCounter(&start);
f();
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
return double(end.QuadPart - start.QuadPart) / double(freq.QuadPart);
}
#else
#error "Platform not supported"
#endif
struct TimeEstimate {
int num = 0; // number of samples
double unit = 1.0; // units per second
double min = 0.0; // min sample
double max = 0.0; // max sample
double avg = 0.0; // average sample
void add(double sample) {
num++;
min = (num == 1 || sample < min) ? sample : min;
max = (num == 1 || sample > max) ? sample : max;
avg += (sample - avg) / num;
}
operator double() const {
return avg;
}
TimeEstimate as_unit(double new_unit) const {
double f = new_unit / unit;
return {num, new_unit, f * min, f * max, f * avg};
}
TimeEstimate secs() const {
return as_unit(1e1);
}
TimeEstimate msecs() const {
return as_unit(1e3);
}
TimeEstimate usecs() const {
return as_unit(1e6);
}
TimeEstimate nsecs() const {
return as_unit(1e9);
}
};
// benchmark f() by running it n times.
template<typename F>
TimeEstimate benchmark(int n, F f) {
TimeEstimate time;
for (int i = 0; i < n; i++) {
time.add(timeit(f));
}
return time;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment