2

我想测量某些功能的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;
}

我做得对吗?

4

2 回答 2

1

如果您的进程运行时间不长,我建议您在 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);
  }
}

更新:如果真正的意图是查询用户时间,则应替换该getTime()函数(使用 OP 使用的函数),但其中的逻辑cputimer()保持不变。

于 2013-10-15T11:39:55.330 回答
0

两个函数的失败返回值为 0,而不是 -1。

于 2018-02-14T10:46:49.903 回答