为什么 boost::timer 给我这样奇怪的结果?
我的工作解决方案是使用关于 gettimeofday
的包装器来自 <time.h>
的函数, 但我不明白为什么 boost::timer
在这里不适合我。我做错了什么?
class Timer {
private:
timeval startTime;
public:
void start(){
gettimeofday(&startTime, NULL);
}
double stop(){
timeval endTime;
long seconds, useconds;
double duration;
gettimeofday(&endTime, NULL);
seconds = endTime.tv_sec - startTime.tv_sec;
useconds = endTime.tv_usec - startTime.tv_usec;
duration = seconds + useconds/1000000.0;
return duration;
}
long stop_useconds(){
timeval endTime;
long useconds;
gettimeofday(&endTime, NULL);
useconds = endTime.tv_usec - startTime.tv_usec;
return useconds;
}
static void printTime(double duration){
printf("%5.6f seconds\n", duration);
}
};
测试:
//test
for (int i = 0; i < 10; i++) {
void *vp = malloc(1024*sizeof(int));
memset((int *)vp, 0, 1024);
void* itab = malloc(sizeof(int)*1024*256); //1MiB table
if (itab) {
memset ( (int*)itab, 0, 1024*256*sizeof (int) );
float elapsed;
boost::timer t;
Timer timer = Timer();
timer.start();
Munge64(itab, 1024*256);
double duration = timer.stop();
long lt = timer.stop_useconds();
timer.printTime(duration);
cout << t.elapsed() << endl;
elapsed = t.elapsed();
cout << ios::fixed << setprecision(10) << elapsed << endl;
cout << ios::fixed << setprecision(10) << t.elapsed() << endl;
printf("Munge8 elapsed:%ld useconds\n", lt);
elapsed = 0;
free(vp);
free(itab);
//printf("Munge8 elapsed:%d\n", elapsed);
}
}
结果:
0.000100 秒
0 << ??????????
40 << ????????????????
40 << ????????????????????????????????????
Munge8 已用:100 useconds
0.000100 秒
0
40
40
Munge8 已用:100 useconds
0.000099 秒
0
40
40
Munge8 已用:99 秒
最佳答案
你不应该使用 boost::timer - http://www.boost.org/doc/libs/1_54_0/libs/timer/doc/original_timer.html#Class计时器
在 POSIX 上它测量 CPU 时间 - 而不是挂钟时间。
考虑使用 boost::chrono 或 std::chrono - 如果您想将自己与系统挂钟的漂移或偏移隔离开来,那么在实现计时器时,您可能希望查看 steady_clock - 作为其他时钟。我希望在 POSIX 上这将在 CLOCK_MONOTONIC 上使用 clock_gettime。
关于c++ - 为什么 boost::timer 的结果如此奇怪?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17665805/