很多时候,我们想要统计一段代码运行的时间,但是这段代码运行的时间很短很短,以至于用clock()等函数获得时间的方法几乎是无效的。
那么我们该粗和获得高时间呢?
很多Intel的CPU有一条获得系统时钟的指令。我们可以用这条指令来获得时间。
rdtsc.h
#if defined(__i386__) static __inline__ unsigned long long rdtsc(void) { unsigned long long int x; __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x)); return x; } #elif defined(__x86_64__) static __inline__ unsigned long long rdtsc(void) { unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 ); } #elif defined(__powerpc__) static __inline__ unsigned long long rdtsc(void) { unsigned long long int result=0; unsigned long int upper, lower,tmp; __asm__ volatile( "0: \n" "\tmftbu %0 \n" "\tmftb %1 \n" "\tmftbu %2 \n" "\tcmpw %2,%0 \n" "\tbne 0b \n" : "=r"(upper),"=r"(lower),"=r"(tmp) ); result = upper; result = result<<32; result = result|lower; return(result); } #endif用法:
#include <stdio.h> #include "rdtsc.h" int main(int argc, char* argv[]) { unsigned long long a,b; start_time = rdtsc(); //do something... end_time = rdtsc(); printf("%llu\n", end_time-start_time); return 0; }有了这个超高精度的时间函数,以后应用中对效率的比较会更准确。
参考:rdtsc详解