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 ?

0

1 Answer 1

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.
3
  • So, that's overall processor time ? Not processor time devoted to the process that executed the clock() function. Commented Oct 22, 2019 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. Commented Oct 22, 2019 at 0:07
  • Thanks, that's very clear. Commented Oct 22, 2019 at 0:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.