High precision timing in userspace in Linux

怎甘沉沦 提交于 2020-01-01 06:35:20

问题


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?


回答1:


clock_gettime allows you to get a nanosecond-precise time from the thread start, process start or epoch.




回答2:


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

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



回答3:


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().




回答4:


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.



来源:https://stackoverflow.com/questions/5165108/high-precision-timing-in-userspace-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!