当前位置:  开发笔记 > 编程语言 > 正文

高分辨率时序部分代码

如何解决《高分辨率时序部分代码》经验,为你挑选了1个好方法。

我想测量循环中函数的速度.但是为什么我这样做的方式总是打印"0"而不是9位十进制精度(即纳秒/微秒)的高分辨率时序?

这样做的正确方法是什么?

#include 
#include 
#include 
int main() {


 for (int i = 0; i <100; i++) {
    std::clock_t startTime = std::clock(); 
    // a very fast function in the middle
    cout << "Time: " << setprecision(9) << (clock() - startTime + 0.00)/CLOCKS_PER_SEC << endl;
 }

 return 0;
}

相关问题:

如何克服clock()低分辨率

具有C++和Linux的高分辨率计时器

QueryPerformanceCounter在OSX上相当于Windows'

Konstantin T.. 6

将时间计算函数for () { .. }移到语句之外,然后将总执行时间与测试循环中的操作数分开.

#include 
#include 
#define NUMBER 10000 // the number of operations

// get the difference between start and end time and devide by
// the number of operations
double diffclock(clock_t clock1, clock_t clock2)
{
    double diffticks = clock1 - clock2;
    double diffms = (diffticks) / (CLOCKS_PER_SEC / NUMBER);
    return diffms;
}

int main() {
    // start a timer here
    clock_t begin = clock();

    // execute your functions several times (at least 10'000)
    for (int i = 0; i < NUMBER; i++) {
        // a very fast function in the middle
        func()
    }

    // stop timer here
    clock_t end = clock();

    // display results here
    cout << "Execution time: " << diffclock(end, begin) << " ms." << endl;
    return 0;
}

注意:std :: clock()缺乏足够的精度来进行性能分析.参考.



1> Konstantin T..:

将时间计算函数for () { .. }移到语句之外,然后将总执行时间与测试循环中的操作数分开.

#include 
#include 
#define NUMBER 10000 // the number of operations

// get the difference between start and end time and devide by
// the number of operations
double diffclock(clock_t clock1, clock_t clock2)
{
    double diffticks = clock1 - clock2;
    double diffms = (diffticks) / (CLOCKS_PER_SEC / NUMBER);
    return diffms;
}

int main() {
    // start a timer here
    clock_t begin = clock();

    // execute your functions several times (at least 10'000)
    for (int i = 0; i < NUMBER; i++) {
        // a very fast function in the middle
        func()
    }

    // stop timer here
    clock_t end = clock();

    // display results here
    cout << "Execution time: " << diffclock(end, begin) << " ms." << endl;
    return 0;
}

注意:std :: clock()缺乏足够的精度来进行性能分析.参考.

推荐阅读
乐韵答题
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有