1

I want to retrieve the amount of time in milliseconds that a process has spent taking up CPU time since the process was started.

I can found in the /proc/<pid>/stat the fields:

  • #14 utime - CPU time spent in user code, measured in clock ticks
  • #15 stime - CPU time spent in kernel code, measured in clock ticks

I think the time I want is:

mytime = utime + stime

Am I right?

And How to convert the utime and stime from clock ticks to milliseconds ?

MOHAMED
  • 41,599
  • 58
  • 163
  • 268
  • If you specify the speed of your processor clock you would be able to work out the conversion to milliseconds! – Jonathan Holland Oct 20 '16 at 11:07
  • Are you trying to get a measure in wall clock time? Because I think this `/proc` technique will be inaccurate for SMP? – Tersosauros Oct 20 '16 at 11:07
  • Much of Linux is open-source, meaning its implementation (code) is freely available. That includes not only the Linux kernel, but also much user-space programs and command-line utilities. For example [the `time` command](http://man7.org/linux/man-pages/man1/time.1.html). If you can find the source to it then you can see how they do to measure time. – Some programmer dude Oct 20 '16 at 11:08
  • Or much more simply, just use [the `getrusage` system call](http://man7.org/linux/man-pages/man2/getrusage.2.html). – Some programmer dude Oct 20 '16 at 11:09
  • The length of a clock tick in seconds is obtained from the CPU frequency. Apply elementary school physics: `t = 1 / f`. Then simply multiply that time with the number of ticks. – Lundin Oct 20 '16 at 11:15
  • @Lundin How to find the cpu frequency ? – MOHAMED Oct 20 '16 at 15:10
  • @Lundin. what I find is `time_ms = time_tick/(CLOCKS_PER_SEC/1000)`. Is it correct ? – MOHAMED Oct 20 '16 at 15:48
  • 1
    @MOHAMED `CLOCKS_PER_SEC/1000` may be integer division and be too inaccurate. Try `time_ms = time_tick*1000/CLOCKS_PER_SEC;` Please post the type of `time_ms` for a good answer. – chux - Reinstate Monica Oct 20 '16 at 15:59
  • @chux time_ms is time in milliseconds and it's unsigned int – MOHAMED Oct 20 '16 at 16:00
  • Check http://stackoverflow.com/q/16726779/2410359 – chux - Reinstate Monica Oct 20 '16 at 16:15

0 Answers0