3

Why boost::timer gives me such strange results? My working solution is to use wrapper about gettimeofday function from <time.h>, but I don't understand why boost::timer is not working for me here. What do I do wrong?

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:

//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);
    }
}

results:

0.000100 seconds

0 << ??????????

40 << ????????????????

40 << ???????????????????????????????????

Munge8 elapsed:100 useconds

0.000100 seconds

0

40

40

Munge8 elapsed:100 useconds

0.000099 seconds

0

40

40

Munge8 elapsed:99 useconds

4

1 回答 1

3

你不应该使用 boost::timer - http://www.boost.org/doc/libs/1_54_0/libs/timer/doc/original_timer.html#Class timer

在 POSIX 上,它测量 CPU 时间 - 而不是挂钟时间。

考虑使用 boost::chrono 或 std::chrono - 如果您想将自己与系统挂钟的漂移或偏移隔离开来,则在实现计时器时,您可能希望查看 stable_clock - 作为其他时钟。我希望在 POSIX 上这将在 CLOCK_MONOTONIC 上使用 clock_gettime。

于 2013-07-16T01:07:33.687 回答