c - 如何获取函数的 RAM 和 CPU 使用率?

标签 c linux windows cpu-usage ram

比方说,我有一个(或多个)函数需要很长时间(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/

相关文章:

windows - 等待任务抛出

c++ 对 c 函数 mbstowcs() 的调用更改参数

c - 为什么会出现内存泄漏呢? (C)

c - 解释如何仅使用这两行 : 在 C 中为二维数组分配和释放内存

c - 以编程方式确定程序是否正在运行

linux - Linux 中的异步定时器

linux - 如何排除一些文件

c# - Windows 中是否有我无法处理的特殊按键事件?

Linux:将IP地址重定向到域名

python - 我在哪里保存 .py 文件,以便我可以从 python 解释器(从 powershell )导入它