Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

c - clock() precision in time.h

I am trying to calculate the number of ticks a function uses to run and to do so an using the clock() function like so:

unsigned long time = clock();
myfunction();
unsigned long time2 = clock() - time;
printf("time elapsed : %lu",time2);

But the problem is that the value it returns is a multiple of 10000, which I think is the CLOCK_PER_SECOND. Is there a way or an equivalent function value that is more precise?

I am using Ubuntu 64-bit, but would prefer if the solution can work on other systems like Windows & Mac OS.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are a number of more accurate timers in POSIX.

  • gettimeofday() - officially obsolescent, but very widely available; microsecond resolution.
  • clock_gettime() - the replacement for gettimeofday() (but not necessarily so widely available; on an old version of Solaris, requires -lposix4 to link), with nanosecond resolution.

There are other sub-second timers of greater or lesser antiquity, portability, and resolution, including:

  • ftime() - millisecond resolution (marked 'legacy' in POSIX 2004; not in POSIX 2008).
  • clock() - which you already know about. Note that it measures CPU time, not elapsed (wall clock) time.
  • times() - CLK_TCK or HZ. Note that this measures CPU time for parent and child processes.

Do not use ftime() or times() unless there is nothing better. The ultimate fallback, but not meeting your immediate requirements, is

  • time() - one second resolution.

The clock() function reports in units of CLOCKS_PER_SEC, which is required to be 1,000,000 by POSIX, but the increment may happen less frequently (100 times per second was one common frequency). The return value must be defined by CLOCKS_PER_SEC to get time in seconds.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...