简体   繁体   English

为什么使用 time.h 计算 function 运行时返回 0 秒

[英]Why is calculating function runtime returning 0 seconds using time.h

I am trying to use time.h to solve for 4 functions runtimes, but my output is returning 0.000000 sec我正在尝试使用 time.h 来解决 4 个函数运行时问题,但我的 output 返回 0.000000 秒

double timep[4] = {0.0};

clock_t begin, end;

begin = clock();
function1();
end = clock();
timep[0] = (double)(end - begin) / CLOCKS_PER_SEC;

begin = clock();
function2();
end = clock();
timep[1] = (double)(end - begin) / CLOCKS_PER_SEC;

begin = clock();
function3();
end = clock();
timep[2] = (double)(end - begin) / CLOCKS_PER_SEC;

begin = clock();
funtion4();
end = clock();
timep[3] = (double)(end - begin) / CLOCKS_PER_SEC;

Printing the timep array using (%lf) yields使用 (%lf) 打印 timep 数组产量

0.000000
0.000000
0.000000
0.000000

It may just be that the functions are relatively fast, combined with the fact the clock often has a minimum resolution (in that it's usually a multiple of some value, supported by your comment that "for some reason the output is rounded, example 1.654000").可能只是功能相对较快,再加上时钟通常具有最小分辨率的事实(因为它通常是某个值的倍数,您的评论支持“出于某种原因,output 被四舍五入,例如 1.654000” )。

A better way to check may be to time many iterations of the function (assuming no side effects that would affect later runs) and divide the total time by the count, something like:更好的检查方法可能是对 function 的多次迭代进行计时(假设没有会影响以后运行的副作用)并将总时间除以计数,例如:

#define QUANT 1000
begin = clock();
for (int i = 0; i < QUANT; ++i)
    function1();
end = clock();
timep[0] = (double)(end - begin) / CLOCKS_PER_SEC / QUANT;

This will amortise the errors that may be produced by the afore-mentioned resolution of the clock.这将分摊上述时钟分辨率可能产生的误差。 A potential error of (for example) +/- 1ms has far less impact on an operation that take 1000ms (the loop of a thousand calls) than one that takes 1ms (a single call). (例如)+/- 1ms 的潜在错误对耗时 1000ms(一千次调用的循环)的操作的影响远小于耗时 1ms(单个调用)的操作。

The latter could give you any value from 0 to 2ms (+/- 100%), the former 999 to 1001ms (+/- 0.1%).后者可以为您提供从 0 到 2ms (+/- 100%) 的任何值,前者为 999 到 1001ms (+/- 0.1%)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM