gpt4 book ai didi

c++ - 使用 GetProcessTimes 在 Windows 上测量 CPU 时间

转载 作者:可可西里 更新时间:2023-11-01 10:25:37 32 4
gpt4 key购买 nike

我想测量CPU一些功能的时间。我知道如何使用 GetProcessTimes,但我在使用某种“重新启动”实现它时遇到了问题:

通常,我会这样做:

#include "stdafx.h"
#include <math.h>
#include <windows.h>

double cputimer()
{
FILETIME createTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;

if ( GetProcessTimes( GetCurrentProcess( ),
&createTime, &exitTime, &kernelTime, &userTime ) != -1 )
{
SYSTEMTIME userSystemTime;
if ( FileTimeToSystemTime( &userTime, &userSystemTime ) != -1 )
return (double)userSystemTime.wHour * 3600.0 +
(double)userSystemTime.wMinute * 60.0 +
(double)userSystemTime.wSecond +
(double)userSystemTime.wMilliseconds / 1000.0;
}
}

int _tmain(int argc, _TCHAR* argv[])
{
double start, stop;
long sum = 0L;

start = cputimer();
for (long long i = 1; i < 10000000; i++){
sum += log((double)i);
}
stop = cputimer();

printf("Time taken: %f [seconds]\n", stop - start);

return 0;
}

但是对于“重置”,我不确定我的结果是否正确:

#include "stdafx.h"
#include <math.h>
#include <windows.h>

#define START 1
#define STOP 0

double cputimer(int reset)
{
FILETIME createTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;

double now = 0, then = 0;

if ( GetProcessTimes( GetCurrentProcess( ),
&createTime, &exitTime, &kernelTime, &userTime ) != -1 )
{
SYSTEMTIME userSystemTime;
if ( FileTimeToSystemTime( &userTime, &userSystemTime ) != -1 )
now = (double)userSystemTime.wHour * 3600.0 +
(double)userSystemTime.wMinute * 60.0 +
(double)userSystemTime.wSecond +
(double)userSystemTime.wMilliseconds / 1000.0;
}

if(reset)
{
then = now;
}
else
{
then = now - then;
}

return then;
}

int _tmain(int argc, _TCHAR* argv[])
{
double s;
long sum = 0L;

cputimer(START);
for (long long i = 1; i < 10000000; i++){
sum += log((double)i);
}
s = cputimer(STOP);


printf("Time taken: %f [seconds]\n", s);

return 0;
}

我做得对吗?

最佳答案

如果您的进程运行时间不长,我建议您在 Windows 上采用更简单的解决方案:

#define WIN32_LEAN_AND_MEAN
#include <windows.h>

double getTime() {
LARGE_INTEGER freq, val;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&val);
return (double)val.QuadPart / (double)freq.QuadPart;
}

然后你可以像这样使用它:

double d0 = getTime();
// function to measure
double timeInMilliseconds = 1000* (getTime() - d0);

您可以将其包装到一个函数中以实现与您的代码类似的行为。

double cputimer(int reset)
{
static double startTime = 0;
if(reset)
{
startTime = getTime();
return 0.0;
} else
{
return 1000* (getTime() - startTime);
}
}

更新:如果真正的目的是查询 usertime应该替换 getTime() 函数(用 OP 使用的函数),但 cputimer() 中的逻辑保持不变。

关于c++ - 使用 GetProcessTimes 在 Windows 上测量 CPU 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19378805/

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