【问题标题】:why such strange results for boost::timer?为什么 boost::timer 的结果如此奇怪?
【发布时间】:2013-07-14 00:00:13
【问题描述】:

为什么 boost::timer 会给我这样奇怪的结果? 我的工作解决方案是使用来自<time.h> 的关于gettimeofday 函数的包装器,但我不明白为什么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 微秒

0.000100 秒

0

40

40

Munge8 经过:100 微秒

0.000099 秒

0

40

40

Munge8 经过:99 微秒

【问题讨论】:

    标签: c++ linux boost time g++


    【解决方案1】:

    你不应该使用 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。

    【讨论】:

    • 谢谢,我错过了现在已弃用,因为我正在查看过时的类引用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多