0

I read http://linux.die.net/man/3/clock_gettime and http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/comment-page-1/#comment-681578

It said to use this to

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &stop_time);

measure how long it take for a function to run.

I tried that in my program. When I run it, it returns saying it took 15 sec. But when I compare against using a stop watch to measure it, it is 30 sec.

Can you please tell me why clock_gettime return 1/2 of the actual time it took?

Thank you.

n179911
  • 19,547
  • 46
  • 120
  • 162
  • possible duplicate of [Understanding the different clocks of clock\_gettime()](http://stackoverflow.com/questions/7506952/understanding-the-different-clocks-of-clock-gettime) – Mahonri Moriancumer May 06 '14 at 00:40

1 Answers1

6

In a multi-process environment, processes are constantly migrating from CPU(s) to 'run queue(s)'.

When performance testing an application, it is often convenient to know the amount of time a process has been running on a CPU, while excluding time that the process was waiting for a CPU resource on a 'run queue'.

In the case of this question, where CPU-time is about half of REAL-time, it is likely that other processes were actively competing for CPU time while your process was also running. It appears that your process was fairly successful in acquiring roughly half the CPU resources during its run.

Instead of using CLOCK_PROCESS_CPUTIME_ID, you might consider using CLOCK_REALTIME?

For additional details, see: Understanding the different clocks of clock_gettime()

Community
  • 1
  • 1
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28
  • 1
    A related question is why I get negative number sometime when I use CLOCK_PROCESS_CPUTIME_ID? – n179911 May 06 '14 at 00:59
  • The negative number is a result of flaws in the Linux kernel, as well as GLIBC; specifically, when the frequency of the CPU clock changes, or (more probable) the process is moved to a different CPU whose may not be fully synchronized to the CPU timer of the current CPU. – Mahonri Moriancumer May 06 '14 at 01:11