[英]What is the fastest linux C time function for calculating time deltas? Seeing poor performance with clock_gettime and gettimeofday
我正在写一个探查器,其用例类似于
long getTiming()
{
long start = someGetTimeFunction();
executeSomething();
return someTimeFunction() - start;
}
无论我使用什么时间函数,似乎都会增加大量开销。 我已经尝试使用CLOCK_MONOTONIC, CLOCK_PROCESS_CPUTIME_ID
和CLOCK_THREAD_CPUTIME_ID
gettimeofday()
, clock_gettime()
尝试,并且尝试了一些在这里找到的汇编程序来调用rdtsc
。
每次运行500,000,这些是它们的成本:
[INFO] [ OK ] X.TimeGetTimeOfDay (1165 ms)
[INFO] [ OK ] X.TimeRdtscl (1208 ms)
[INFO] [ OK ] X.TimeMonotomicGetTime (1536 ms)
[INFO] [ OK ] X.TimeProcessGetTime (1575 ms)
[INFO] [ OK ] X.TimeThreadGetTime (1522 ms)
这是在Macbook Pro上运行的CentOS 5虚拟盒VM上。
由于我需要计算增量,因此不需要绝对时间。 而且,没有风险比较在smp系统上不同内核或CPU上获得的时间。
我可以做得更好吗?
这是我的测试用例:
TEST(X, TimeGetTimeOfDay)
{
for (int i = 0; i < 500000; i++) {
timeval when;
gettimeofday(&when, NULL);
}
}
TEST(X, TimeRdtscl)
{
for (int i = 0; i < 500000; i++) {
unsigned long long when;
rdtscl(&when);
}
}
TEST(X, TimeMonotomicGetTime)
{
for (int i = 0; i < 500000; i++) {
struct timespec when;
clock_gettime(CLOCK_MONOTONIC, &when);
}
}
TEST(X, TimeProcessGetTime)
{
for (int i = 0; i < 500000; i++) {
struct timespec when;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &when);
}
}
TEST(X, TimeThreadGetTime)
{
for (int i = 0; i < 500000; i++) {
struct timespec when;
clock_gettime(CLOCK_THREAD_CPUTIME_ID, &when);
}
}
这是我从这里得到的rdtsc。
inline void rdtscl(unsigned long long *t)
{
unsigned long long l, h;
__asm__ __volatile__ ("rdtsc" : "=a"(l), "=d"(h));
*t = ( (unsigned long long)l)|( ((unsigned long long)h) <<32 );
}
我创建了一个单独的线程,每1 ms更新一次boost :: atomic的时间。
我的执行线程读取了这么长时间的时间戳。
吞吐量要好得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.