gpt4 book ai didi

c - 如何找到C语言代码的执行时间?

转载 作者:行者123 更新时间:2023-11-30 20:23:41 25 4
gpt4 key购买 nike

我找到了这个代码here 。如果我除(t2-t1)/CLOCK_PER_SEC我会得到以秒为单位的时间吗?如何找到 CLOCK_PER_SEC?有没有更好的方法来查找代码或函数的执行时间?

#include<time.h> 
main()
{
clock_t t1=clock();
// Your code that takes more than 1 sec;
clock_t t2=clock();
printf("The time taken is.. %g ", (t2-t1));
..

最佳答案

你可以这样做:

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

typedef struct timeval wallclock_t;

void wallclock_mark(wallclock_t *const tptr)
{
gettimeofday(tptr, NULL);
}

double wallclock_since(wallclock_t *const tptr)
{
struct timeval now;
gettimeofday(&now, NULL);

return difftime(now.tv_sec, tptr->tv_sec)
+ ((double)now.tv_usec - (double)tptr->tv_usec) / 1000000.0;
}

int main(void)
{
wallclock_t t;
double s;

wallclock_mark(&t);

/*
* Do something
*/

s = wallclock_since(&t);
printf("That took %.9f seconds wall clock time.\n", s);
return 0;
}

您可以在我的 Time measurements 中阅读更多内容.

关于c - 如何找到C语言代码的执行时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35683615/

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