简体   繁体   English

在C中定时功能

[英]Timing a function in C

I'm trying to find out the time it takes for a function to execute in C. What i'm trying is the following: 我试图找出函数在C中执行所需的时间。我正在尝试的是以下内容:

#include <time.h>

time_t start;
time_t finish;
double seconds;

time(&start);
FUNCTION
time(&finish);

seconds = difftime(finish,start);

printf("Time taken is %.f", seconds);

However, the returned value is always the same for different functions: 1389133144 seconds. 但是,对于不同的函数,返回值始终相同:1389133144秒。

Any help? 有帮助吗? Thanks! 谢谢!

Other approach I commonly use is something like this: 我经常使用的其他方法是这样的:

#include <sys/time.h>

//this is from http://www.cs.usfca.edu/~peter/ipp/
#define GET_TIME(now) { \
   struct timeval t; \
   gettimeofday(&t, NULL); \
   now = t.tv_sec + t.tv_usec/1000000.0; \
}

//in your code
double start, end;
GET_TIME(start);
//... do some stuff...
GET_TIME(end);

printf("TOTAL TIME = %f secs\n", end-start);

The time function returns the number of seconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). time函数返回自Epoch,1970-01-01 00:00:00 +0000(UTC)以来的秒数。 If the argument is non- NULL , it also stores the time in it. 如果参数为非NULL ,则它还将时间存储在其中。

1389133144 is actually a pretty reasonable timestamp, it is 2014-01-07 22:19:04. 1389133144实际上是一个非常合理的时间戳,它是2014-01-07 22:19:04。

However, the time function is not a very good tool to measure the run time of a function, since the precision is very low. 但是, time函数不是测量函数运行时间的非常好的工具,因为精度非常低。 Consider using gettimeofday , clock_gettime or simply clock , all of which should be more precise. 考虑使用gettimeofdayclock_gettime或简单的clock ,所有这些都应该更精确。

The problem isn't in the time calculations, its in the format specifier for the printf() statement. 问题不在于时间计算,而是在printf()语句的格式说明符中。 You are using "%.f", where you probably want "%f". 您正在使用“%。f”,您可能需要“%f”。 The . 的。 means precision in this context. 在这种情况下意味着精确。

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

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