目前我通过调用以秒为单位获取程序的执行时间:
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);
是否有可能以毫秒为单位获得挂墙时间?如果有怎么办?
如果您使用的是 POSIX-ish 机器,请gettimeofday()
改用;这为您提供了合理的便携性和微秒级分辨率。
稍微深奥一点,但也在 POSIX 中,是clock_gettime()
函数,它为您提供纳秒级分辨率。
在许多系统上,您会发现一个ftime()
实际上以秒和毫秒为单位返回时间的函数。但是,它不再出现在单一 Unix 规范中(与 POSIX 大致相同)。你需要标题<sys/timeb.h>
:
struct timeb mt;
if (ftime(&mt) == 0)
{
mt.time ... seconds
mt.millitime ... milliseconds
}
这至少可以追溯到第 7 版(或第 7 版)Unix,因此它已被广泛使用。
我的亚秒计时器代码中也有注释times()
,clock()
它再次使用了其他结构和标题。我也有关于使用clock()
每秒 1000 个时钟滴答(毫秒计时)的 Windows 的注释,以及GetTickCount()
在 Windows 95 上注明为必要但在 NT 上没有的旧接口。
如果您可以在程序本身之外执行此操作,则在 linux 中,您可以使用time
命令 ( time ./my_program
)。
我最近写了一篇博文,解释了如何跨平台获取以毫秒为单位的时间。
它会像 time(NULL) 一样工作,但会在 windows 和 linux 上从 unix 纪元返回毫秒数而不是秒数。
#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
}
如果需要,您可以修改它以返回微秒而不是毫秒。
开源 GLib 库有一个声称提供微秒精度的 GTimer 系统。该库可在 Mac OS X、Windows 和 Linux 上使用。我目前正在使用它在 Linux 上进行性能计时,它似乎工作得很好。
gprof
,它是 GNU 工具包的一部分,是一个选项。大多数 POSIX 系统都会安装它,并且它在 Cygwin for Windows 下可用。跟踪自己使用的时间gettimeofday()
效果很好,但它的性能相当于使用打印语句进行调试。如果您只想要一个快速而肮脏的解决方案,那很好,但它不如使用适当的工具那么优雅。
要使用gprof
,您必须在编译时指定 -pg 选项,gcc
如下所示:
gcc -o prg source.c -pg
然后就可以gprof
在生成的程序上运行如下:
gprof prg > gprof.out
默认情况下,gprof 会生成程序的整体运行时间,以及每个函数花费的时间、每个函数被调用的次数、每个函数调用的平均时间以及类似信息。
您可以使用 设置大量选项gprof
。如果您有兴趣,可以在手册页或通过 Google 获得更多信息。
在 Windows 上,使用 QueryPerformanceCounter 和关联的 QueryPerformanceFrequency。他们没有给你一个可以转换为日历时间的时间,所以如果你需要,那么使用 CRT API 询问时间,然后立即使用 QueryPerformanceCounter。然后,您可以做一些简单的加法/减法来计算日历时间,但由于连续执行 API 所需的时间会出现一些错误。嘿,这是一台PC,你期待什么???