在 C++ 中暂停执行的最快方法是什么

What is the fastest way to pause execution in c++

我想在 C++ 中暂停执行时间,这是我得到的代码:

while (_run)
{
    //pause code
    std::this_thread::sleep_for(std::chrono::nanoseconds(_interval_ns));

    //doing stuff
    _counter++;
    (*_mainSrcTick)(GetDeltaTime(), GetName());
    
    for (auto obj : _physicsList)
    {
        PyObject_CallMethod(obj, "PhysicsTick", "(d)", GetDeltaTime());
    }
    
    //used to mesure time
    LastTick = std::chrono::high_resolution_clock::now();
}

以防万一这里是我的增量时间函数,它获取自上次报价以来我的间隔已经过去了多少次:

double difference = std::chrono::duration<double,std::nano>(std::chrono::high_resolution_clock::now() - LastTick).count();
double result = difference/_interval_ns  ;
return result;

我遇到的问题是,如果不暂停,显然我的代码可以 运行 在我们几个人中,暂停一小会儿,即使这需要几毫秒。所以我想要一种不会对我的程序造成太大干扰的暂停方式。

在你想知道我知道如何使用“使用命名空间”和这个项目 运行s on x64 之前(尽管我不介意它是否也可以在 x86 上 运行),链接 python 与 c++ 并且是多线程的,尽管仅在 python 端。所以我想我需要一种更快的方法来暂停或至少需要时间,以便它可以用 while 循环暂停。我不想要 ANY 第三方依赖项。我使用 VS 2019.

目的是让事情以每个 _interval_ns 的固定频率发生。 GetDeltaTime 是这样我可以给 dostuff 任何不准确的地方,但如果频率准确而不是增量时间会更好。我正在寻找微秒级精度,nano 会很好。

当你让你的线程休眠时,操作系统没有安排它,重新安排它需要一些时间。如果您想暂停很短的时间,请使用 _mm_pause()。根据您自己对系统花费的时间的测量,您可能希望执行固定次数。英特尔表示在 Skylake 上需要 140 个周期(在旧的 CPUs 上花费的时间要少得多):https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=_mm_pause&expand=5146

如果你想休眠的时间很少,但又关心实际已经过了多少时间,你可以在循环中检查时间,并在每个循环中调用一次 _mm_pause()clock_gettime() 的大约 70 ns 加上 _mm_pause() 的 40 ns 应该会给你在 Skylake 上大约 120 ns 的分辨率。

在任何一种情况下,您都不会显式释放 CPU 内核以供其他进程使用,并且 OS 可能会在有其他线程等待 [=28] 时取消调度您的线程=] 在同一个核心上。因此,您需要设置 CPU 亲和力,以便在同一核心上没有其他东西可以 运行。有关详细信息,请参阅 https://www.suse.com/support/kb/doc/?id=000017747

另请参阅:https://software.intel.com/content/www/us/en/develop/articles/benefitting-power-and-performance-sleep-loops.html

如果您不想为线程上下文切换付费,请考虑不切换线程上下文,例如使用 coroutines.Here Gor Nishanov claims that suspending and resuming a coroutine takes less than a nanosecond