Linux 精准计时-暨计算程序或函数执行的时间

在网上找了好久,发现Linux 各种时间函数:

gettimeofday() 能精确到准us(微秒)级,具体的精度跟内核有关.

clock_gettime()能精确到准ns(纳秒)级,经测试,该函数自身的开销一般是几十ns,不过怎么也比gettimeofday()的精度更高了。

还有使用内联汇编取cpu 的计数器,并且跟具体的cpu相关,并且在SMP系统上不准,不是很实用


计算 System time & User Time:

times() 函数

需 include <sys/times.h>

具体的例子以后有心情了再补;


读取 cpu 时间戳,需使用内联汇编

(Pentium 及其兼容的CPU ):

gcc,  例子:volatile 关键字不能少,不然会被gcc优化掉

unsigned long long read_tsc(void)
{
    unsigned long long val;
    asm volatile("rdtsc" : "=A" (val));
    return val;
}
或者:

inline unsigned long long read_tsc(void)
{
    asm volatile("rdtsc"); 
}
根据以上函数读出两次cpu的不同的时间戳,然后除以 cpu 的主频(>1Ghz),可以得到 ns 级的时间精度.

问题1:现在的cpu通常都带有频率自调节功能,cpu频率也不是一个定值,目前还没想到有啥好办法。

问题2:多核cpu的线程可能在不同的核心切换,不能保证读取的tsc值的有效性,也许只能在主线程读取这个值

计算 Real Time:

微妙(us) gettimeofday()

#include <sys/time.h> 
    /*
     * 函数原型为
     * int gettimeofday(struct timeval *tv, struct timezone *tz);
     * 
     * timeval结构体定义
     * struct timeval 
     * {
     *     long int tv_sec; // 秒数
     *     long int tv_usec; // 微秒数
     * }
     * 
     */
    
    //例子
    timeval tv;
    gettimeofday(&tv,NULL);
纳秒(ns) clock_gettime

这个函数自身的开销在 2.3G的cpu上不超过 100ns

//函数原型和 timespec 结构为:

#include <time.h>

int clock_gettime(clockid_t clk_id, struct timespec *tp);

//常用的 clickid 为:其中 CLOCK_PROCESS_CPUTIME_ID CLOCK_THREAD_CPUTIME_ID在 SMP系统中貌似不准确
    CLOCK_REALTIME
    // System-wide real-time clock.  Setting this clock requires appro-priate privileges.

    CLOCK_PROCESS_CPUTIME_ID
    //High-resolution per-process timer from the CPU.

    CLOCK_THREAD_CPUTIME_ID
    //Thread-specific CPU-time clock.

struct timespec 
{
     time_t tv_sec; /* seconds */
     long tv_nsec; /* nanoseconds */
};


posted on 2013-04-03 17:24  存在的存在  阅读(1118)  评论(0编辑  收藏  举报

导航