Linux时间统计函数

Linux下用来获取时间,以及计算时间消耗的函数总结

参考http://stackoverflow.com/questions/12392278/measure-time-in-linux-getrusage-vs-clock-gettime-vs-clock-vs-gettimeofday

  • time() returns the wall-clock time from the OS, with precision in seconds.
  • clock() seems to return the sum of user and system time. At one time this was supposed to be the CPU time in cycles, but modern standards require CLOCKS_PER_SEC to be 1000000, giving a maximum possible precision of 1 µs. The precision on my system is indeed 1 µs. This clock wraps around once it tops out (this typically happens after ~2^32 ticks, which is not very long for a 1 MHz clock). 只统计了cpu计算时间,如果有io等待,那么clock返回的时间少于wall-clock
  • clock_gettime(CLOCK_MONOTONIC, ...) provides nanosecond resolution, is monotonic. I believe the 'seconds' and 'nanoseconds' are stored separately, each in 32-bit counters. Thus, any wrap-around would occur after many dozen years of uptime. This looks like a very good clock, but unfortunately it isn't yet available on OS X. 可以达到ns级别的精度
  • getrusage() turned out to be the best choice for my situation. It reports the user and system times separately and does not wrap around. The precision on my system is 1 µs, but I also tested it on a Linux system (Red Hat 4.1.2-48 with GCC 4.1.2) and there the precision was only 1 ms.可到进程使用的系统资源详细信息
  • gettimeofday() returns the wall-clock time with (nominally) µs precision. On my system this clock does seem to have µs precision, but this is not guaranteed, because "the resolution of the system clock is hardware dependent". 最常用的得到wall-clock时间函数
  • mach_absolute_time() is an option for very high resolution (ns) timing on OS X. On my system, this does indeed give ns resolution. In principle this clock wraps around, however it is storing ns using a 64-bit unsigned integer, so the wrapping around shouldn't be an issue in practice. Portability is questionable.

你可能感兴趣的:(Linux时间统计函数)