Can clock() be used as a dependable API to measure time taken by CPU to execute a snippet of code? When verified usng times() / clock(), both do not seem to measure the CPU
On recent Linux's (*). you can get this information from the /proc filesystem. In the file /proc/PID/stat
the 14th entry has the number of jiffies used in userland code and the 15th entry has the number of jiffies used in system code.
If you want to see the data on a per-thread basis, you should reference the file /proc/PID/task/TID/stat
instead.
To convert jiffies to microseconds, you can use the following:
define USEC_PER_SEC 1000000UL
long long jiffies_to_microsecond(long long jiffies)
{
long hz = sysconf(_SC_CLK_TCK);
if (hz <= USEC_PER_SEC && !(USEC_PER_SEC % hz))
{
return (USEC_PER_SEC / hz) * jiffies;
}
else if (hz > USEC_PER_SEC && !(hz % USEC_PER_SEC))
{
return (jiffies + (hz / USEC_PER_SEC) - 1) / (hz / USEC_PER_SEC);
}
else
{
return (jiffies * USEC_PER_SEC) / hz;
}
}
If all you care about is the per-process statistics, getrusage
is easier. But if you want to be prepared to do this on a per-thread basis, this technique is better as other then the file name, the code would be identical for getting the data per-process or per-thread.
* - I'm not sure exactly when the stat file was introduced. You will need to verify your system has it.