0

我希望能够计算应用程序特定部分的执行时间。
这是一个简化的代码来显示我无法理解的内容:

#include <stdio.h>
#include <time.h>

void fun(){
    double result = 0;
    for (int i = 1; i<200;i++){
        for (int j = 1; j<200;j++){
            result += i/j;              // Random mathematical expression
        }
    }
}

int main(int argc, char const *argv[])
{
    clock_t start, end;

    start = clock();

    fun();

    end = clock();  

    clock_t clocks_taken = (end - start);
    double total_time = ((double)(end - start)/CLOCKS_PER_SEC)*1000; //millisec

    printf("Clock cycles: %d. Total time: %lf ms", clocks_taken, total_time);
}

给出输出:

Clock cycles: 0. Total time: 0.000000 ms

据我所知,时钟周期是处理器的一次执行,嵌套的 forloop 应该需要数百个周期?还是我弄错了?

即使当前示例没有,我也需要能够测量大约需要 1 毫秒的任务的执行时间。如果重要的话,我正在 Windows 中构建和运行该应用程序。

4

1 回答 1

1

您不使用result,因此不需要计算它。由于您的函数没有任何可观察的功能,因此几乎不需要任何时间。对“玩具”代码进行基准测试毫无意义。

请注意,“时钟周期”不是 CPU 时钟周期。它们是某种 CPU 使用计时器的周期,可能会以惊人的大增量滴答作响。你CLOCKS_PER_SEC的平台上有什么?

于 2020-08-26T07:14:31.873 回答