【发布时间】:2018-08-18 10:28:25
【问题描述】:
我正在尝试使用物理时钟来测量 c++ 中某些命令的执行时间,但我遇到了一个问题,即从计算机上的物理时钟读取测量值的过程可能需要很长时间。代码如下:
#include <string>
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <time.h>
int main()
{
int64_t mtime, mtime2, m_TSsum, m_TSssum, m_TSnum, m_TSmax;
struct timespec t0;
struct timespec t1;
int i,j;
for(j=0;j<10;j++){
m_TSnum=0;m_TSsum=0; m_TSssum=0; m_TSmax=0;
for( i=0; i<10000000; i++) {
clock_gettime(CLOCK_REALTIME,&t0);
clock_gettime(CLOCK_REALTIME,&t1);
mtime = (t0.tv_sec * 1000000000LL + t0.tv_nsec);
mtime2= (t1.tv_sec * 1000000000LL + t1.tv_nsec);
m_TSsum += (mtime2-mtime);
m_TSssum += (mtime2-mtime)*(mtime2-mtime);
if( (mtime2-mtime)> m_TSmax ) { m_TSmax = (mtime2-mtime);}
m_TSnum++;
}
std::cout << "Average "<< (double)(m_TSsum)/m_TSnum
<< " +/- " << floor(sqrt( (m_TSssum/m_TSnum - ( m_TSsum/m_TSnum ) *( m_TSsum/m_TSnum ) ) ) )
<< " ("<< m_TSmax <<")" <<std::endl;
}
}
接下来我在专用核心上运行它(或者系统管理员告诉我的),以避免进程被调度程序移动到后台的任何问题:
$ taskset -c 20 ./a.out
这是我得到的结果:
Average 18.0864 +/- 10 (17821)
Average 18.0807 +/- 8 (9116)
Average 18.0802 +/- 8 (8107)
Average 18.078 +/- 6 (7135)
Average 18.0834 +/- 9 (21240)
Average 18.0827 +/- 8 (7900)
Average 18.0822 +/- 8 (9079)
Average 18.086 +/- 8 (8840)
Average 18.0771 +/- 6 (5992)
Average 18.0894 +/- 10 (15625)
很明显,调用clock_gettime() 需要大约 18 纳秒(在此特定服务器上),但我无法理解为什么“最大”时间似乎要长 300 到 1000 倍?
如果我们假设核心真正专用于这个进程并且没有被其他东西使用(这可能是也可能不是真的;当不在专用核心上运行时,平均时间是相同的,但 sd/max 是更大一些),还有什么可能导致这些“减速”(因为没有更好的名字)?
【问题讨论】:
-
如果您可以访问 C++11,您可能需要考虑使用
<chrono>insteaf ogtime.h -
探索
std::chrono。 -
阅读(并使用)std::chrono。
-
专用内核并不意味着同一个内核不处理操作系统中断。对于纳秒精度,您需要查看 RTOS。
-
std::chrono不会变魔术——在幕后它只会委托给clock_gettime或其他类似的电话。
标签: c++ linux performance x86 clock