C语言 如何在C中以毫秒为单位获得程序的执行时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2215744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the execution time of a program in milliseconds in C?
提问by alex
Currently I'm getting the execution wall time of my program in secondsby calling:
目前,我通过调用以秒为单位获取程序的执行时间:
time_t startTime = time(NULL);
//section of code
time_t endTime = time(NULL);
double duration = difftime(endTime, startTime);
Is it possible to get the wall time in milliseconds? If so how?
是否有可能以毫秒为单位获得墙壁时间?如果是这样怎么办?
采纳答案by Jonathan Leffler
If you're on a POSIX-ish machine, use gettimeofday()instead; that gives you reasonable portability and microsecond resolution.
如果您使用的是 POSIX-ish 机器,请gettimeofday()改用;这为您提供了合理的便携性和微秒分辨率。
Slightly more esoteric, but also in POSIX, is the clock_gettime()function, which gives you nanosecond resolution.
稍微深奥一点,但也在 POSIX 中,是该clock_gettime()函数,它为您提供纳秒级分辨率。
On many systems, you will find a function ftime()that actually returns you the time in seconds and milliseconds. However, it is no longer in the Single Unix Specification (roughly the same as POSIX). You need the header <sys/timeb.h>:
在许多系统上,您会发现一个函数ftime()实际上以秒和毫秒为单位返回时间。但是,它不再出现在 Single Unix Specification 中(与 POSIX 大致相同)。你需要标题<sys/timeb.h>:
struct timeb mt;
if (ftime(&mt) == 0)
{
mt.time ... seconds
mt.millitime ... milliseconds
}
This dates back to Version 7 (or 7th Edition) Unix at least, so it has been very widely available.
这至少可以追溯到第 7 版(或第 7 版)Unix,因此它已被广泛使用。
I also have notes in my sub-second timer code on times()and clock(), which use other structures and headers again. I also have notes about Windows using clock()with 1000 clock ticks per second (millisecond timing), and an older interface GetTickCount()which is noted as necessary on Windows 95 but not on NT.
我的亚秒级计时器代码中还有关于times()and 的注释clock(),它们再次使用其他结构和标题。我也有关于 Windows 使用clock()每秒 1000 个时钟滴答(毫秒计时)的注释,以及一个旧的接口GetTickCount(),在 Windows 95 上被认为是必要的,但在 NT 上没有。
回答by poundifdef
If you can do this outside of the program itself, in linux, you can use timecommand (time ./my_program).
如果您可以在程序本身之外执行此操作,则在 linux 中,您可以使用time命令 ( time ./my_program)。
回答by Thomas Bonini
I recently wrote a blog post that explains how to obtain the time in milliseconds cross-platform.
我最近写了一篇博文,解释了如何跨平台获取时间(以毫秒为单位)。
It will work like time(NULL), but will return the number of milliseconds instead of seconds from the unix epoch on both windows and linux.
它会像 time(NULL) 一样工作,但会返回 Windows 和 Linux 上 unix epoch 中的毫秒数而不是秒数。
Here is the code
这是代码
#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
}
You can modify it to return microseconds instead of milliesconds if you want.
如果需要,您可以修改它以返回微秒而不是毫秒。
回答by Swiss
gprof, which is part of the GNU toolkit, is an option. Most POSIX systems will have it installed, and it's available under Cygwin for Windows. Tracking the time yourself using gettimeofday()works fine, but it's the performance equivalent of using print statements for debugging. It's good if you just want a quick and dirty solution, but it's not quite as elegant as using proper tools.
gprof是 GNU 工具包的一部分,是一个选项。大多数 POSIX 系统都会安装它,并且可以在 Cygwin for Windows 下使用它。自己使用跟踪时间gettimeofday()工作正常,但它的性能相当于使用打印语句进行调试。如果您只是想要一个快速而肮脏的解决方案,那很好,但它不如使用适当的工具那么优雅。
To use gprof, you must specify the -pg option when compiling with gccas in:
要使用gprof,您必须在编译时指定 -pg 选项,gcc如下所示:
gcc -o prg source.c -pg
Then you can run gprofon the generated program as follows:
然后就可以gprof在生成的程序上运行如下:
gprof prg > gprof.out
By default, gprof will generate the overall runtime of your program, as well as the amount of time spent in each function, the number of times each function was called, the average time spent in each function call, and similar information.
默认情况下,gprof 会生成你程序的整体运行时间,以及每个函数花费的时间、每个函数被调用的次数、每个函数调用花费的平均时间,以及类似的信息。
There are a large number of options you can set with gprof. If you're interested, there is more information in the man pages or through Google.
您可以使用 设置大量选项gprof。如果您有兴趣,可以在手册页或通过 Google 获取更多信息。
回答by Bob Murphy
The open-source GLib library has a GTimer system that claims to provide microsecond accuracy. That library is available on Mac OS X, Windows, and Linux. I'm currently using it to do performance timings on Linux, and it seems to work perfectly.
开源 GLib 库有一个 GTimer 系统,声称可以提供微秒精度。该库可在 Mac OS X、Windows 和 Linux 上使用。我目前正在使用它在 Linux 上进行性能计时,它似乎工作得很好。
回答by David Gladfelter
On Windows, use QueryPerformanceCounter and the associated QueryPerformanceFrequency. They don't give you a time that is translatable to calendar time, so if you need that then ask for the time using a CRT API and then immediately use QueryPerformanceCounter. You can then do some simple addition/subtraction to calculate the calendar time, with some error due to the time it takes to execute the API's consecutively. Hey, it's a PC, what did you expect???
在 Windows 上,使用 QueryPerformanceCounter 和关联的 QueryPerformanceFrequency。它们不会为您提供可转换为日历时间的时间,因此如果您需要,请使用 CRT API 询问时间,然后立即使用 QueryPerformanceCounter。然后,您可以进行一些简单的加法/减法来计算日历时间,但由于连续执行 API 所需的时间而存在一些错误。嘿,这是一台电脑,你期待什么???

