目前我通过调用以下方法来获取我的程序的执行时间(以秒为单位):
time_t startTime = time(NULL);
//section of code
time_t endTime = time(NULL);
double duration = difftime(endTime, startTime);
是否可以以毫秒为单位获取墙上时间?如果可以,如何实现?
目前我通过调用以下方法来获取我的程序的执行时间(以秒为单位):
time_t startTime = time(NULL);
//section of code
time_t endTime = time(NULL);
double duration = difftime(endTime, startTime);
是否可以以毫秒为单位获取墙上时间?如果可以,如何实现?
gettimeofday()
函数,它具有合理的可移植性和微秒级别分辨率。clock_gettime()
,它可以提供纳秒级别的分辨率。ftime()
的函数,它可以返回以秒和毫秒为单位的时间。然而,此函数已不再属于Single Unix规范(大致等同于POSIX)。您需要包含头文件 <sys/timeb.h>
。struct timeb mt;
if (ftime(&mt) == 0)
{
mt.time ... seconds
mt.millitime ... milliseconds
}
gettimeofday()
在POSIX 2008中被正式标记为“过时”。这并不意味着它很快就会消失,但预示着它的命运已经注定。 - Jonathan Leffler#ifdef WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif
/* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
* windows and linux. */
int64 GetTimeMs64()
{
#ifdef WIN32
/* Windows */
FILETIME ft;
LARGE_INTEGER li;
uint64 ret;
/* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
* to a LARGE_INTEGER structure. */
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
ret = li.QuadPart;
ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */
return ret;
#else
/* Linux */
struct timeval tv;
uint64 ret;
gettimeofday(&tv, NULL);
ret = tv.tv_usec;
/* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
ret /= 1000;
/* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
ret += (tv.tv_sec * 1000);
return ret;
#endif
}
如果您想要,您可以将其修改为返回微秒而不是毫秒。
time
命令(time ./my_program
)来实现。该命令可以计算出程序运行的时间。gprof
是GNU工具包的一部分,是一个选项。大多数POSIX系统都会安装它,并且在Windows下的Cygwin中也可以使用。使用gettimeofday()
自己跟踪时间是可行的,但这相当于使用打印语句进行调试的性能等效方法。如果您只想要一个快速而简单的解决方案,那么这很好,但它不如使用适当的工具优雅。
要使用gprof
,必须在使用gcc
编译时指定-pg选项,如下所示:
gcc -o prg source.c -pg
gprof
:gprof prg > gprof.out
默认情况下,gprof将生成程序的总运行时间,以及每个函数中花费的时间,每个函数被调用的次数,每个函数调用中平均花费的时间等信息。
您可以使用大量选项设置gprof
。如果您感兴趣,可以在man页面或通过Google获取更多信息。
开源GLib库具有GTimer系统,声称提供微秒级精度。该库可在Mac OS X、Windows和Linux上使用。我目前正在Linux上使用它来进行性能计时,它似乎完美地工作。