【问题标题】:Using clock() to measure time in C使用clock()在C中测量时间
【发布时间】:2017-04-10 20:16:34
【问题描述】:

我已经编写了这段代码,但它没有返回正确的时间(可能某些代码是错误的)。还有其他方法可以比这个(在c中)更精确地测量两个动作之间的时间吗?

float measureTime(clock_t start, clock_t end){

    float totalSeconds;    

    totalSeconds = ((long double)(end - start))/CLOCKS_PER_SEC;

    printf("%.6f", totalSeconds);

    return(totalSeconds);
}

int main(){

    clock_t start, end;

    start = clock();
    //piece of code here
    //
    end = clock();

    measureTime(start, end);

    return (EXIT_SUCCESS);
}

【问题讨论】:

  • 适当的时间是什么意思?
  • 什么是CLOCKS_PER_SEC
  • @MarkYisri,这是time.h中定义的常量。
  • clock() 测量 CPU 时间,而不是实时。
  • ...除了 MSVC 的 clock() 是非标准的,它测量挂壁时间。

标签: c time


【解决方案1】:

正如 Weather Vane 所说,在 c 中测量时间存在许多问题。这是一个How do I measure time in C?

只是对您的方法的评论,如果您的代码包含很少的执行行,您可能会得到 0.0s 的结果(如果您使用具有更高频率的 4 cpu 的现代计算机,则代码将在几个时钟周期)。

【讨论】:

    猜你喜欢
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    相关资源
    最近更新 更多