这个 C++ 程序给出了可变的结果。有时变化很大。我调用 getrusage() 一次来获取开始时间。然后我循环调用 rand() 500000000 次。然后我再次调用 getrusage() 并输出两个 getrusage() 调用之间经过的用户和系统时间。根据它包含的内容,我可以理解为什么“系统时间”会不一致。但我预计“用户时间”是(主进程)线程处于运行状态的时间。我认为从一次运行到下一次运行将非常接近完全一致。但事实并非如此。
#include <iostream>
#include <exception>
#include <cstdlib>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
using std::cout;
// tm is end time on intput, time different from start to end on output.
void since(const struct timeval start, struct timeval &tm)
{
if (tm.tv_sec == start.tv_sec)
{
tm.tv_sec = 0;
tm.tv_usec -= start.tv_usec;
}
else
{
tm.tv_usec += 1000000 - start.tv_usec;
tm.tv_sec -= start.tv_sec;
if (tm.tv_usec >= 1000000)
{
tm.tv_usec -= 1000000;
++tm.tv_sec;
}
}
}
void out_tm(const struct timeval &tm)
{
cout << "seconds: " << tm.tv_sec;
cout << " useconds: " << tm.tv_usec;
}
void bail(const char *msg)
{
cout << msg << '\n';
std::terminate();
}
int main()
{
struct rusage usage;
if (getrusage(RUSAGE_SELF, &usage))
bail("FAIL: getrusage() call failed");
struct timeval user_tm = usage.ru_utime;
struct timeval sys_tm = usage.ru_stime;
for (unsigned i = 0; i < 500000000; ++i)
std::rand();
if (getrusage(RUSAGE_SELF, &usage))
bail("FAIL: getrusage() call failed");
since(user_tm, usage.ru_utime);
user_tm = usage.ru_utime;
since(sys_tm, usage.ru_stime);
sys_tm = usage.ru_stime;
cout << "User time: ";
out_tm(user_tm);
cout << "\nSystem time: ";
out_tm(sys_tm);
cout << '\n';
return(0);
}