gpt4 book ai didi

c - 如何使用 struct timeval 获取执行时间?

转载 作者:太空狗 更新时间:2023-10-29 16:45:35 36 4
gpt4 key购买 nike

看完this article关于运行时间,我写了一个简单的代码来计算一个循环的执行时间:

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char** argv) {
struct timeval, tvalBefore, tvalAfter;

gettimeofday (&tvalBefore, NULL);
int i =0;
while ( i < 1000) {
i ++;
}

gettimeofday (&tvalAfter, NULL);

printf("Time in microseconds: %0.3f microseconds\n",
(float)(tvalAfter.tv_sec - tvalBefore.tv_sec)
)
return 0;
}

clang 编译器给我以下错误:

print_time.c:7:16: error: expected identifier or '('
struct timeval, *tvalBefore, *tvalAfter;
^
print_time.c:13:17: error: use of undeclared identifier 'tvalBefore'
gettimeofday (&tvalBefore, NULL);
^
print_time.c:19:17: error: use of undeclared identifier 'tvalAfter'
gettimeofday (&tvalAfter, NULL);
^
print_time.c:22:12: error: use of undeclared identifier 'tvalAfter'
(float)(tvalAfter.tv_sec - tvalBefore.tv_sec)
^
print_time.c:22:31: error: use of undeclared identifier 'tvalBefore'
(float)(tvalAfter.tv_sec - tvalBefore.tv_sec)
^
5 errors generated.

我不知道我的代码有什么问题,知道吗?

最佳答案

您的代码中有两个输入错误:

 struct timeval,

应该是

 struct timeval

printf() 括号后需要一个分号。

另外,根据编译器的不同,如此简单的循环可能会被优化掉,无论你做什么,都会给你 0 微秒的时间。

最后是时间计算错误。您只考虑秒,忽略微秒。您需要得到秒之间的差异,乘以一百万,然后添加“之后”tv_usec 并减去“之前”tv_usec。将整数秒数转换为 float 将一无所获。

我建议查看 struct timeval 的手册页。

这是代码:

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char** argv) {
struct timeval tvalBefore, tvalAfter; // removed comma

gettimeofday (&tvalBefore, NULL);
int i =0;
while ( i < 10000) {
i ++;
}

gettimeofday (&tvalAfter, NULL);

// Changed format to long int (%ld), changed time calculation

printf("Time in microseconds: %ld microseconds\n",
((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
+tvalAfter.tv_usec) - tvalBefore.tv_usec
); // Added semicolon
return 0;
}

关于c - 如何使用 struct timeval 获取执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12722904/

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