如何取得进程及其子进程的CPU资源
问题: 在进程中需要调用其它程序,统计该程序的CPU时间。
使用下面的几种方法,得到不同的结果:
(1) if ((pid=fork())==0)
{
if (execv(command, NULL)==-1)
cout<<"child process exec error."<<endl;
exit(0);
}
else if (pid>0)
{
wait3(&status,0,&ru);
if (limit.statics) PrintStatics(ru, true);
}
输出ru的用户时间和系统时间
(2)用时钟差:
clock_t _timer=clock();
if ((pid=fork())==0)
{
if (execv(command, NULL)==-1)
cout<<"child process exec error."<<endl;
exit(0);
}
else if (pid>0)
{
wait3(&status,0,&ru);
if (limit.statics) PrintStatics(ru, true);
}
clock_t ticks = clock () - _timer;
long s = ticks / CLOCKS_PER_SEC;
_sec += s;
_msec += (ticks - s*CLOCKS_PER_SEC)*1000/CLOCKS_PER_SEC;
if (_msec >= 1000)
{
_msec -= 1000;
_sec++;
}
输出s
(3) 使用time命令:
time my_program
这几种方法的输出结果不一样。其中(2)输出的都是0 (1)输出的时间比(3)要多