我在 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/