I am trying to compare the times measured by c++11 std::chrono::high_resolution_clock
and the rdtsc_clock
clock at below. From the high_resolution_clock
, I am getting result like 11000, 3000, 1000, 0. From the rdtsc_clock
, I am getting 134, 15, 91 etc. Why their result look so differently? From my gut feeling, I believe the rdtsc_clock
is presenting the ~accurate results, am I right?
template<std::intmax_t clock_freq>
struct rdtsc_clock {
typedef unsigned long long rep;
typedef std::ratio<1, clock_freq> period;
typedef std::chrono::duration<rep, period> duration;
typedef std::chrono::time_point<rdtsc_clock> time_point;
static const bool is_steady = true;
static time_point now() noexcept
{
unsigned lo, hi;
asm volatile("rdtsc" : "=a" (lo), "=d" (hi));
return time_point(duration(static_cast<rep>(hi) << 32 | lo));
}
};
The timing code:
typedef std::chrono::high_resolution_clock Clock;
//typedef rdtsc_clock<3300000000> Clock;
typedef std::chrono::nanoseconds nanoseconds;
typedef std::chrono::duration<double, typename Clock::period> Cycle;
for(int n=0; n < 10; n++){
auto t1 = Clock::now();
//codes
auto t2 = Clock::now();
printf(%.0f ns \n", duration_cast<nanoseconds>(Cycle(t2 - t1)).count());
}