我正在测试我的计算机有关数据对齐的速度。测试很简单,处理同一个缓冲区,一次获取2个字节,一次获取4个字节,而不是8个字节。使用2字节访问权处理剩余(如果存在)的几个字节。测试详细描述here。我的问题是,当我在循环中执行此操作时,经过的时间我会得到完全相同的printf结果-显然这是不正确的,并且可以在循环开始时设置断点得到确认-然后新结果似乎是正确的。因此,我认为这与编译器优化有关(但我为g ++设置了-O0标志),但是我不知道确切是什么,我也不了解。g ++ 4.4.7 Ubuntu 12.10 NetBeans AMDx64那我该怎么办?for (int i = 0; i < 10; i++) { int* itab=new int[1000*256]; //1MiB table double elapsed=0; boost::timer* t=new boost::timer(); Munge16(itab, 250); elapsed = t->elapsed(); printf("Munge8 elapsed:%d\n", elapsed); t->restart(); delete t; elapsed=0; delete itab;}结果:使用过Munge8:1721468076使用过Munge8:1721468076使用过Munge8:1721468076使用过Munge8:1721468076使用过Munge8:1721468076使用过Munge8:1721468076使用过Munge8:1721468076使用过Munge8:1721468076使用过Munge8:1721468076使用过Munge8:1721468076这里有断点: for (int i = 0; i < 10; i++) {breakpoint >> int* itab=new int[1000*256]; //1MiB tableMunge8逝世:1721528944蒙格经历了8:1721529048Munge8已逝:1721529174使用过Munge8:1721529281使用过Munge8:1721529496使用过Munge8:1721529554使用过Munge8:1721529643使用过Munge8:1721529756Munge8逝世:1721529808Munge8已逝:1721529896有一个解决方案,但是我仍然不明白为什么boost :: timer给我这么奇怪的结果。可行的解决方案是使用gettimeofday中的<time.h>函数。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); }};测试://testfor (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毫秒0.000100秒04040Munge8经过的时间:100毫秒0.000099秒04040Munge8经过的时间:99毫秒 (adsbygoogle = window.adsbygoogle || []).push({}); 最佳答案 您不应该使用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视为其他时钟。 (adsbygoogle = window.adsbygoogle || []).push({});
10-01 03:22