我正在尝试比较 c++11 测量的时间std::chrono::high_resolution_clock
和rdtsc_clock
下面的时钟。从high_resolution_clock
,我得到类似 11000、3000、1000、0 的结果。从rdtsc_clock
,我得到 134、15、91 等。为什么它们的结果看起来如此不同?从我的直觉来看,我相信rdtsc_clock
正在呈现〜准确的结果,对吗?
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));
}
};
计时码:
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());
}