I would like to measure the system time it takes to execute some code. To do this I know I would sandwich said code between two calls to getrusage(), but I get some unexpect
Use gprof. This will give give you the time taken by each function. Install gprof and use these flags for compilation -pg -fprofile-arcs -ftest-coverage.
You should use usage.ru_utime
, which is user CPU time used, instead.
You're misunderstanding the difference between "user" and "system" time. Your example code is executing primarily in user-mode (ie, running your application code) while you are measuring, but "system" time is a measure of time spent executing in kernel-mode (ie, processing system calls).
ru_stime
is the correct field to measure system time. Your test application just happens not to accrue any such time between the two points you check.