如何计算C ++中的代码片段的执行时间 [英] How to Calculate Execution Time of a Code Snippet in C++
问题描述
我必须以秒为单位计算C ++代码段的执行时间。它必须在Windows或Unix计算机上工作。
I have to compute execution time of a C++ code snippet in seconds. It must be working either on Windows or Unix machines.
我使用代码执行以下代码。 (import before)
I use code the following code to do this. (import before)
clock_t startTime = clock();
// some code here
// to compute its execution duration in runtime
cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
但是对于小输入或短语句,如a = a + 1,结果。
However for small inputs or short statements such as a = a + 1, I get "0 seconds" result. I think it must be something like 0.0000001 seconds or something like that.
我记得 System.nanoTime()
在Java中工作相当不错在这种情况下。但是我不能从C ++的 clock()
函数获得完全相同的功能。
I remember that System.nanoTime()
in Java works pretty well in this case. However I can't get same exact functionality from clock()
function of C++.
?
推荐答案
您可以使用我写的这个函数。你调用 GetTimeMs64()
,并返回从使用系统时钟的unix纪元以来经过的毫秒数 - 就像 time(NULL)
,除非在毫秒。
You can use this function I wrote. You call GetTimeMs64()
, and it returns the number of milliseconds elapsed since the unix epoch using the system clock - the just like time(NULL)
, except in milliseconds.
它适用于windows和linux;它是线程安全的。
It works on both windows and linux; it is thread safe.
请注意,窗口的粒度为15 ms;在Linux上它是实现依赖的,但它通常也是15毫秒。
Note that the granularity is 15 ms on windows; on linux it is implementation dependent, but it usually 15 ms as well.
#ifdef _WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif
/* Remove if already defined */
typedef long long int64; typedef unsigned long long uint64;
/* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
* windows and linux. */
uint64 GetTimeMs64()
{
#ifdef _WIN32
/* Windows */
FILETIME ft;
LARGE_INTEGER li;
/* 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;
uint64 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;
gettimeofday(&tv, NULL);
uint64 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
}
这篇关于如何计算C ++中的代码片段的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!