This C++ program gives variable results. Sometimes the variation is large. I call getrusage() once to get the start time. Then I call rand() 500000000 times in a loop. Then I call getrusage() again and output the elapsed user and system time between the two getrusage() calls. Depending on what it includes, I can understand why "system time" would not be consistent. But I expected "user time" to be the time the (main process) thread was in the running state. I thought it would be very close to completely consistent from one run to the next. But it's not.
#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);
}