使用C ++测量多线程应用程序中全局时间(挂钟)的最快方法

问题描述 投票:1回答:1

我正在开发一个高性能库,我需要在完成计算后停止线程的时间点,然后将该时间点保存在全局变量中,以便此全局变量始终保持最近的完成时间。线。

现在,我正在使用带有时间戳的C ++ std:chrono库来停止时间,如:

auto start = std::chrono::high_resolution_clock::now().time_since_epoch();
// thread calculates something
auto finish = std::chrono::high_resolution_clock::now().time_since_epoch();
unsigned time = std::chrono::duration_cast<std::chrono::microseconds>(finish-start).count();
// now I can use the needed time and also update a global variable with the finish time point.

这非常有效。但...

对chrono的调用比调用rdtsc()要慢。

rdtsc版本:

static __inline__ ticks getticks(void)
{
     unsigned a, d;
     asm("cpuid");
     asm volatile("rdtsc" : "=a" (a), "=d" (d));

     return (((ticks)a) | (((ticks)d) << 32));
}

tick = getticks();
sleep(1); // or whatever calculation
tick1 = getticks();
time = (unsigned)((tick1-tick)/2400000/*The CPU speed*/);

比较:我测量了chrono和rdtsc,调用rdtsc本身来查看他们需要多少滴答,结果如下:

  • 计时需要大约34096个刻度
  • rdtsc需要大约1744个滴答声

问题:

我不能使用rdtsc,因为据我所知,它只是相对的。我不能用它来衡量时间点,对吗?我不想只是一些计算的持续时间,而是实际的完成时间点,以便每个线程都知道最近的完成时间是什么时候发生的。

问题:衡量全球时间点并在所有线程中共享的最快方法是什么?

c++ multithreading time chrono
1个回答
2
投票

我不能使用rdtsc因为它只是我所知的相对而言。

它与某些未指明的时间点相关,例如CPU通电时间。

我不能用它来衡量时间点,对吗?

您使用rdtsc来测量CPU周期的持续时间。您还可以将该值用作未指定时间以来的时间点。您还可以找到该未指定时间的挂钟时间。


如果你使用gcc__builtin_ia32_rdtsc generates better assembly than hand-coded versions

© www.soinside.com 2019 - 2024. All rights reserved.