C 在 linux 和 windows 上获取 cpu 使用率

标签 c windows linux io cpu

我在 linux 和 windows 上使用以下程序来获取当前进程的 cpu 利用率。

Linux:

int main()
{
      int ret;
      char *buf;
      int i=0;
      int who= RUSAGE_SELF;
      struct rusage usage;
      struct rusage *p=&usage;

      ret=getrusage(who,p);
      printf("user time used: %16lf  %16lf\n",p->ru_utime.tv_sec,p->ru_utime.tv_usec);
    printf("system time used: %16lf  %16lf\n",p->ru_stime.tv_sec,p->ru_stime.tv_usec);

      system("ls");
      printf("user time used: %16lf  %16lf\n",p->ru_utime.tv_sec,p->ru_utime.tv_usec);
    printf("system time used: %16lf  %16lf\n", p->ru_stime.tv_sec,p->ru_stime.tv_usec);    

    return 0;
}

Linux 上的输出:

user time used: 0.000000 -1.999568
system time used: 0.000000 -1.999568
a.out check.c
user time used: 0.000000 -1.999568
system time used: 0.000000 -1.999568

这是否意味着 system("ls") 命令没有占用任何 cpu 周期来执行?我如何获得任何命令或程序使用的确切 CPU 周期?

我在 Windows 上遇到了类似的问题。对于下面的代码。

Windows :

int main()
{
    int i=0;
    HANDLE hProcess = GetCurrentProcess();
    FILETIME ftCreation, ftExit, ftKernel, ftUser;
    SYSTEMTIME stKernel;
    SYSTEMTIME stUser;

    GetProcessTimes(hProcess, &ftCreation, &ftExit, &ftKernel, &ftUser);
    FileTimeToSystemTime(&ftKernel, &stKernel);
    FileTimeToSystemTime(&ftUser, &stUser);

    printf("\nTime in kernel mode = %uh %um %us %ums", stKernel.wHour,stKernel.wMinute, stKernel.wSecond, stKernel.wMilliseconds);
    printf("\nTime in user mode = %uh %um %us %ums \n", stUser.wHour,stUser.wMinute, stUser.wSecond, stUser.wMilliseconds);

    system("dir");

    GetProcessTimes(hProcess, &ftCreation, &ftExit, &ftKernel, &ftUser);
    FileTimeToSystemTime(&ftKernel, &stKernel);
    FileTimeToSystemTime(&ftUser, &stUser);

    printf("\nTime in kernel mode = %uh %um %us %ums", stKernel.wHour,stKernel.wMinute, stKernel.wSecond, stKernel.wMilliseconds);
    printf("\nTime in user mode = %uh %um %us %ums \n", stUser.wHour,stUser.wMinute, stUser.wSecond, stUser.wMilliseconds);
    system("PAUSE");
    return 0;
}

以上程序windows输出 dev c++:

Time in kernel mode: 0h 0m 0s 15ms
Time in user mode: 0h 0m 0s 15ms
<directory listing>
Time in kernel mode: 0h 0m 0s 15ms
Time in user mode: 0h 0m 0s 15ms

能否请您告诉我如何才能获得上述程序的正确 cpu 使用率?还有一种方法可以了解 IO 使用情况或读写磁盘/内存的字符数吗? 提前致谢。

最佳答案

在 Linux 版本中,您要求 RUSAGE_SELF,这是父进程的所有线程,而不是子进程的 RUSAGE_CHILDREN。对于 Linux 下的 IO 使用,您需要 2.6.20 之后的内核,并查看 /proc/[pid]/io

我想你在 Windows 上也有类似的问题。您需要使用 CreateProcess而不是 system,这样您就可以获得子进程的句柄并记录它的时间。对于 Windows 上的 IO 使用,我认为您需要使用 WMI,这是一个很大的主题。

关于C 在 linux 和 windows 上获取 cpu 使用率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5272470/

相关文章:

c - (x % y) 和 (x & (y-1)) 等价吗?

c - 在 C 中将字节数组写回到磁盘上的原始状态

c - 使用 LDAP_MATCHING_RULE_IN_CHAIN 的嵌套搜索

android - adb 看不到适用于 android 实例的 visual studio 模拟器

java - Windows 和 Linux 中用于 Java 代码的路径定界符

linux - xvfb 和 xvfb-run 之间有区别吗?

c - 包含多个头文件的方法

windows - 检测任务栏图标闪烁

php - Linux 权限和 PHP - 组

linux - 在 bash 脚本中,$'\0' 的计算结果是什么?为什么?