How does calculate work?

in particular, what does the following code do?

return ((((a->ru_utime.tv_sec * 1000000 + a->ru_utime.tv_usec) -
(b->ru_utime.tv_sec * 1000000 + b->ru_utime.tv_usec)) +
((a->ru_stime.tv_sec * 1000000 + a->ru_stime.tv_usec) -
(b->ru_stime.tv_sec * 1000000 + b->ru_stime.tv_usec)))
/ 1000000.0);

per getrusage's man page, ru_time and ru_stime are members of type struct timeval. each of those has two members:

1. tv_sec is the number of whole seconds of an elapsed time.

2. tv_usec is the number of additional microseconds of that elapsed time.

in other words, an elapsed time is tv_sec seconds + tv_usec microseconds (see why multiplying tv_sec by 1000000?).

ru_utime represents the user CPU time used — the time, up to a particular point, that the processor took to execute code in user mode (a restricted mode where the code has no direct access to the underlying hardware).

ru_stime represents the system CPU time used — the time, up to a particular point, that the processor took to execute code in kernel mode (an unrestricted mode where the code has direct access to the underlying hardware).

of course the times mentioned above are in the context of our program, speller, since we passed RUSAGE_SELF as the first argument to getrusage.

when calling getrusage before and after calling a particular function, we're basically taking elapsed user and system CPU times before and after the call.

calculating the difference between the user CPU times gives us the total user CPU time (in microseconds) used by the function (let's call the result of the following expression userTime):

(a->ru_utime.tv_sec * 1000000 + a->ru_utime.tv_usec) -
(b->ru_utime.tv_sec * 1000000 + b->ru_utime.tv_usec)

calculating the difference between the system CPU times gives us the total system CPU time (in microseconds) used by the function (let's call the result of the following expression systemTime):

(a->ru_stime.tv_sec * 1000000 + a->ru_stime.tv_usec) -
(b->ru_stime.tv_sec * 1000000 + b->ru_stime.tv_usec)

summing up the total user and system CPU times (userTime + systemTime) gives us the total time used by the function (in microseconds).

dividing the result by 1000000.0 gives us that time in seconds.