比方说,我有一个(或多个)函数需要很长时间(wall time)来执行,例如:
#include "stdafx.h"
#include <math.h>
#include <windows.h>
void fun()
{
long sum = 0L;
for (long long i = 1; i < 10000000; i++){
sum += log((double)i);
}
}
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;
start = cputimer();
fun();
stop = cputimer();
printf("Time taken: %f [seconds]\n", stop - start);
return 0;
}
我想测量此函数的 CPU 负载和此函数调用使用的 RAM 使用情况。那可能吗?我怎样才能做到这一点?我对 Windows 和 Linux 解决方案很感兴趣。
最佳答案
在 POSIX 上,您可以尝试使用 getrusage
以类似于您检查墙上时间的方式。不确定 Windows。
关于c - 如何获取函数的 RAM 和 CPU 使用率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19469962/