0

I'm trying to count the time it takes for a code segment to complete. But I'm not looking to determine the time it takes for the process to run, but rather the time it took all things considered, eg if the process gets interrupted I want to count that time as well.

I'm using clock() to do that. Does clock() clock count overall time or process run time ?

1

You don't mention, so I'll assume you're asking about Linux specifically.

From man 3 clock:

The value returned is the CPU time used so far as a clock_t; to get the number of seconds used, divide by CLOCKS_PER_SEC.

That is, clock is only related to processor time. If you want wall time, you can either:

  • Check the start time field of /proc/.../stat with something equivalent to awk -v RS=\) '{ print $20 }' /proc/.../stat, which contains the start time of the process in clock ticks since boot. You can then compare the current uptime from sysinfo() to work out how long has elapsed since process start (although, annoyingly, you need to then convert the uptime to clocks by dividing with CLK_TCK). Or,
  • Use clock_gettime with CLOCK_MONOTONIC, although this has a different API from clock. For one, you explicitly need to call clock_gettime at the start and store the result, using that for comparison (although you may already do that, depending on how you use clock). You'd also need to be ok with this being a time_t instead of a clock_t, although you can go back using CLK_TCK.
| improve this answer | |
  • So, that's overall processor time ? Not processor time devoted to the process that executed the clock() function. – Jim Oct 22 '19 at 0:04
  • @Jim clock() returns the CPU time used by the current process, not systemwide. Both of the possibilities in this answer show the wall time of the current process, which would also include things like being preempted or being taken off the CPU for other reasons. – Chris Down Oct 22 '19 at 0:07
  • Thanks, that's very clear. – Jim Oct 22 '19 at 0:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.