c++ - 如何在 C++ 中计算代码片段的执行时间

标签 c++ benchmarking

我必须以秒为单位计算 C++ 代码片段的执行时间。它必须在 Windows 或 Unix 机器上运行。

我使用以下代码来执行此操作。 (之前导入)

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,我得到“0 秒”的结果。我认为它必须是 0.0000001 秒或类似的东西。

我记得 Java 中的 System.nanoTime() 在这种情况下工作得很好。但是我无法从 C++ 的 clock() 函数中获得完全相同的功能。

你有解决办法吗?

最佳答案

你可以使用我写的这个函数。您调用 GetTimeMs64(),它使用系统时钟返回自 unix 纪元以来经过的毫秒数 - 就像 time(NULL) 一样,但以毫秒为单位。

它适用于 windows 和 linux;它是线程安全的。

注意,windows 上的粒度是 15 毫秒;在 linux 上,它取决于实现,但通常也是 15 毫秒。

#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++ - 如何在 C++ 中计算代码片段的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1861294/

相关文章:

c++ - OpenGl 代码不适用于带有 VS2013 CPP 的 cocos2dx-3.0

c++ - 我看到很多 _GLOBAL__sub_I__ 也来自未使用和剥离的函数,如何删除它们

java - D lang 简单基准测试

java - 如何用 Java 编写正确的微基准测试?

c++ - linux中动态链接库的开源c++代码覆盖率

c++ - 使用 push_back 和 getline 时如何减少临时对象?

c++ - Visual Studio 2017 Linux C++库

PHP json_decode() 输出 : Object vs Array?

java - 测量生产环境中 Java Web 服务的方法执行时间

java - 如何用 Java 编写正确的微基准测试?