gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 11:35:17 26 4
gpt4 key购买 nike

我必须以秒为单位计算 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com