gpt4 book ai didi

c - 我的C程序中的输出有问题(给出了意外的输出)

转载 作者:行者123 更新时间:2023-12-03 07:40:08 26 4
gpt4 key购买 nike

该程序有什么问题,应该计算每个函数调用的运行时间,但是令我惊讶的是,运行时间始终为零,因为beginend完全相同。有人对此有解释吗?
这是我得到的输出:

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(NULL)代替clock()

time_t t1 = clock();

// your code

time_t t2 = clock();

printf("%f", (double)(t2 - t1) / CLOCKS_PER_SEC); // you have to divide it to CLOCKS_PER_SEC (1 000 000) if you want time in seconds
time()以秒为单位进行度量,因此,如果您的程序不花1秒钟,您将不会看到差异
stackoverflow中的某个人已经回答了它们之间的区别 time() vs clock()

关于c - 我的C程序中的输出有问题(给出了意外的输出),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65615660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com