'Measuring time of the process/thread in user mode and in kernel on behalf of the process/thread

Imagine process/thread is running from point A to point B.

I can get how much time the code execution took by taking two gettimeofday() and calculating the difference (wall clock time). However, it may happen, that during the 'route' from A to B CPU was switching to another processes, to drivers, kernel, and other stuff it must perform to keep system running.

Is it possible somehow identify how much time A to B took in terms of actual process/thread execution, and kernel time related to their execution?

The goal for this exercise is to actually identify how much time CPU was NOT executing process/thread or its system calls by executing something else that them.

I am using C.



Solution 1:[1]

Searching the man-pages from time (1) backwards I found this: You can use getrusage:

getrusage() returns resource usage measures

can be used for the own process (self), child processes or the calling thread.

Amongst other values it will give you the user CPU time used and the system CPU time used.

Please see man 2 getrusage for the details. (Or use an online replacement like https://linux.die.net/man/2/getrusage)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cyberbrain