首页 > 解决方案 > C++ 热循环使计时和功能准确,但占用 20% 的 CPU

问题描述

嘿伙计们,这是我关于 Stack Overflow 的第一个问题,所以如果我做错了什么,我的错。

我的程序旨在在特定时间进行精确的鼠标移动,它使用一些硬编码变量和一个计时函数来计算时间,该函数以微秒为单位运行以确保准确性。该程序按预期完美运行,并在正确的时间做出正确的动作等。

唯一的问题是,我正在使用的睡眠函数是一个热循环(例如,它是一个没有睡眠的 while 循环),所以当程序执行这些动作时,它可能会占用高达 20% 的 CPU 使用率。其背景是在游戏中,并且可以将游戏中的 FPS 从 60 降低到 30 并且有很多卡顿,使游戏无法玩。我仍在学习 c++,因此非常感谢任何帮助。下面是我的一些代码片段,以显示我要解释的内容。

这是在某些上下文中调用睡眠的地方

        void foo(paramenters and stuff not rly important)
        {
            Code is doing a bunch of movement stuff here not important blah blah
           
            //after doing its first movement of many, it calls this sleep function from if statement (Time::Sleep) so it knows how long to sleep before executing the next movement.
            if (repeat_delay - animation > 0) Time::Sleep(repeat_delay - animation, excess);
        }

现在这是实际的睡眠功能,在使用 Visual Studio 性能调试器后,我可以看到它正在使用我所有的资源。这个函数中的所有参数都已经考虑过了,就像我之前说的,除了性能之外,代码工作得很好。

#include "Time.hpp"
#include <windows.h>

namespace Time
{
    void Sleep(int64_t sleep_ms, std::chrono::time_point<std::chrono::steady_clock> start) 
    {
        sleep_ms *= 1000;
        auto truncated = (sleep_ms - std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count()) / 1000;
        while (std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count() < sleep_ms)
        {
            if (truncated)
            {
                std::this_thread::sleep_for(std::chrono::milliseconds(truncated));
                truncated = 0;
            }
            /*
            I have attempted putting even a 1 microsecond sleep in here, which brings CPU usage down to 
            0.5% 
            which is great, but my movements slowed right down, and even after attempting to speed up
            the movements manually by altering a the movement functions mouse speed variable, it just 
            makes the movements inaccurate. How can I improve performance here without sacrificing 
            accuracy
            */
        }
    }
}

标签: c++performanceloopstime

解决方案


你为什么要写一个睡眠函数?只需使用std::this_thread::sleep_for,因为它不使用任何资源并且相当准确。

它的准确性可能取决于平台。在我的 Windows 10 PC 上,它在 1 毫秒内准确,这应该适用于超过 10 毫秒(= 100 fps)的持续时间。


推荐阅读