【发布时间】:2021-01-07 15:53:14
【问题描述】:
这个程序有什么问题,它应该计算每个函数调用的经过时间,但令我惊讶的是,经过时间总是零,因为begin 和end 完全相同。有人对此有解释吗?
这是我得到的输出:
TIMING TEST: 10000000 calls to rand()
2113 6249 23817 12054 7060 9945 26819
13831 6820 14149 13035 30858 13924 26467
4268 11314 28400 5239 4496 27757 21452
10878 25064 9049 6508 29612 11373 29913
10234 31769 16167 24553 1875 23992 30606
2606 19539 2184 14832 27089 27474 23310
, .. , ,
End time: 1610034404
Begin time: 1610034404
Elapsed time: 0
Time for each call:,10f
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NCALLS 10000000
#define NCOLS 7
#define NLINES 7
int main(void) {
int i, val;
long begin, diff, end;
begin = time(NULL);
srand(time(NULL));
printf("\nTIMING TEST: %d calls to rand()\n\n", NCALLS);
for (i = 1; i <= NCALLS; ++i) {
val = rand();
if (i <= NCOLS * NLINES) {
printf("%7d", val);
if (i % NCOLS == 0)
putchar('\n');
} else
if (i == NCOLS * NLINES + 1)
printf("%7s\n\n", ", .. , ,");
}
end = time(NULL);
diff = end - begin;
printf("%s%ld\n%s%ld\n%s%ld\n%s%,10f\n\n",
"End time: ", end,
"Begin time: ", begin,
"Elapsed time: ", diff,
"Time for each call:", (double)diff / NCALLS);
return 0;
}
【问题讨论】:
-
是不是因为这个过程只需要几毫秒(改变时间太短了)?
-
time()返回整秒,你可能想要clock_gettime()或gettimeofday()之类的东西。 -
当
i > 50时,你的for循环实际上什么都不做,一个好的编译器会发现它并在50 号之后优化循环。 -
@AdrianMole 假设它可以确定循环后不使用 PRNG 的状态。这是可能的,但可能性不大。
-
@DavidSchwartz 是的。我尝试了 OP 的代码,但在循环中添加了
sum += val- 它仍然显示零秒。
标签: c error-handling