【问题标题】:Using clock() to measure execution time使用clock()测量执行时间
【发布时间】:2012-10-05 09:08:21
【问题描述】:

我正在运行一个使用 GCC 和专有 DSP 交叉编译器的 C 程序来模拟一些功能。我正在使用以下代码来测量程序特定部分的执行时间:

clock_t start,end;
printf("DECODING DATA:\n");
start=clock();
conv3_dec(encoded, decoded,3*length,0);
end=clock();
duration = (double)(end - start) / CLOCKS_PER_SEC;
printf("DECODING TIME = %f\n",duration);

conv3_dec() 是在我的程序中定义的函数,我想找到该函数的运行时间。

现在问题是,当我的程序运行时,conv3_dec() 函数运行了将近 2 个小时,但 printf("DECODING TIME = %f\n",duration) 的输出表明该函数的执行仅在半秒内完成 (DECODING TIME = 0.455443)。这让我很困惑。

我之前使用clock_t 技术来测量程序的运行时间,但差异从未如此巨大。这是由交叉编译器引起的吗?顺便说一句,模拟器模拟了一个运行频率仅为 500MHz 的 DSP 处理器,因此 DSP 处理器的时钟速度差异和我的 CPU 导致错误是测量 CLOCKS_PER_SEC。

【问题讨论】:

    标签: c cross-compiling simulator


    【解决方案1】:

    clock 测量的是 CPU 时间,而不是挂钟时间。由于您没有在 cpu 上运行大部分代码,因此这不是正确的工具。

    【讨论】:

    • 我明白你的意思,但模拟器是一个软件模拟器,所以本质上它是在 CPU 上运行的......无论如何,你能不能建议一些我可以用来测量准确运行时间的东西。 ..谢谢
    【解决方案2】:

    对于像两个小时这样的持续时间,我不会太在意clock(),它对于测量亚秒级的持续时间要有用得多。

    如果您想要实际经过的时间,只需使用time(),例如(为丢失的内容提供的虚拟内容):

    #include <stdio.h>
    #include <time.h>
    
    // Dummy stuff starts here
    #include <unistd.h>
    #define encoded 0
    #define decoded 0
    #define length 0
    static void conv3_dec (int a, int b, int c, int d) {
        sleep (20);
    }
    // Dummy stuff ends here
    
    int main (void) {
        time_t start, end, duration;
        puts ("DECODING DATA:");
        start = time (0);
        conv3_dec (encoded, decoded, 3 * length, 0);
        end = time (0);
        duration = end - start;
        printf ("DECODING TIME = %d\n", duration);
        return 0;
    }
    

    生成:

    DECODING DATA:
    DECODING TIME = 20
    

    【讨论】:

      【解决方案3】:

      gettimeofday()函数也可以考虑。


      gettimeofday() 函数将获取当前时间,以从 Epoch 开始的秒和微秒表示,并将其存储在 tp 指向的 timeval 结构中。系统时钟的分辨率未指定。


      Calculating elapsed time in a C program in milliseconds

      http://www.ccplusplus.com/2011/11/gettimeofday-example.html

      【讨论】:

      • getimeofday 根本不应该考虑:手册页说 - gettimeofday() 返回的时间受系统时间不连续跳转的影响(例如,如果系统管理员手动更改系统时间)。如果您需要一个单调递增的时钟,请参阅clock_gettime(2)。 Opengroup 说 - 应用程序应该使用 clock_gettime() 函数而不是过时的 gettimeofday() 函数。
      • 当一个国家/地区更改其时区或打开/关闭夏令时时,系统时间也会跳跃
      猜你喜欢
      • 2017-04-10
      • 1970-01-01
      • 2011-11-20
      • 2021-06-23
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 2011-02-27
      相关资源
      最近更新 更多