简体   繁体   中英

High precision timing in userspace in Linux

Right now, I'm trying to determine a method to measure the time that a particular function will take (something like pthread_create). Now, of course, these types of functions are extremely optimized to take as little time as possible; so little, in fact, that my timer that uses gettimeofday in userspace which measures in microseconds is unable to adequately measure anything.

Normally, if I could mess with the kernel, I'd use something like get_cycles to measure the raw number of cycles as a performance metric. However, I haven't found a way to do this in userspace. Is there a way to use get_cycles (or an equivalent) or some other higher precision timer I could use in userspace to measure extremely fast functions?

Use RDTSC (if you're on x86), or clock_gettime

unsigned long long cycleCount() {
  asm ("rdtsc");
}

clock_gettime允许您从线程启动,进程启动或纪元获得纳秒精确的时间。

Have you tried getting the time it takes to execute your function, say, 10000 times and taking the mean? That would save the bother of finding more accurate timing functions.

Having said that, this answer: Is gettimeofday() guaranteed to be of microsecond resolution? seems to indicate better functions to use than gettimeofday() .

My linux man page tells me

CONFORMING TO

SVr4, 4.3BSD. POSIX.1-2001 describes gettimeofday() but not settimeofday(). POSIX.1-2008 marks gettimeofday() as obsolete, recomending the use of clock_gettime(2) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM