Bench Timers
Last updated on
I had to need to record a whole bunch of timestamps, and I was curious on the overhead that each timer had. So this is alittle microbenchmark.
Code
#include <stdint.h>
#include <x86intrin.h>
#include <chrono>
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
int
main() {
uint64_t start, end;
/* rdtsc */
__builtin_ia32_rdtsc(); /* warm up the path */
start = __builtin_ia32_rdtsc();
uint64_t call = __builtin_ia32_rdtsc();
end = __builtin_ia32_rdtsc();
printf("RDTSC: %d\n",(int)(end - start));
/* std::chrono */
std::chrono::high_resolution_clock::now(); /* warm up the path */
start = __builtin_ia32_rdtsc();
auto chrono = std::chrono::high_resolution_clock::now();
end = __builtin_ia32_rdtsc();
printf("std::chrono: %d\n",(int)(end - start));
/* clock_gettime */
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts); /* warm up the path */
start = __builtin_ia32_rdtsc();
clock_gettime(CLOCK_MONOTONIC, &ts);
end = __builtin_ia32_rdtsc();
printf("clock_gettime: %d\n",(int)(end - start));
/* gettimeofday; */
struct timeval tv;
gettimeofday(&tv, nullptr); /* warm up the path */
start = __builtin_ia32_rdtsc();
gettimeofday(&tv, nullptr);
end = __builtin_ia32_rdtsc();
printf("gettimeofday: %d\n",(int)(end - start));
return 0;
}
Compile and Run
clang++ timer_test.cpp -std=c++11 -O2 && ./a.out
Results
RDTSC | std::chrono | clock_gettime | gettimeofday |
---|---|---|---|
36 | 354 | 231 | 138 |
Times are in cycles using rdtsc counter
I got similar results on different machines. How important this is to you will be application specific. For I only needed to know so I could understand the overhead in the results. RDTSC while tempting may have issues for your needs.