c++ - 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
*/
}
}
}
解决方案
你为什么要写一个睡眠函数?只需使用std::this_thread::sleep_for
,因为它不使用任何资源并且相当准确。
它的准确性可能取决于平台。在我的 Windows 10 PC 上,它在 1 毫秒内准确,这应该适用于超过 10 毫秒(= 100 fps)的持续时间。
推荐阅读
- python - 将关系相关列添加到多对多表flask-sqlalchemy?
- maven - 使用 maven 在 Cucumber 中运行测试子集
- sql-server - sys.dm_db_missing_index_group_stats 和 last_user_scan 始终为 NULL
- android - Kotlin Android - 当主活动添加项目时,从 Fragment 刷新 ListView
- db2 - 使用 db2 中另一个表的 SUM 更新表
- javascript - 在某些设备上快速滚动时无法正确检测到滚动到底部
- r - 如何为带有百分比标签的条形图创建函数
- php - 使用PHP在mysql中存储阿拉伯语将文本转换为u0645u0631u062du0628u0627
- react-native - 为什么 RNFS 不能在 iOS 中将文件写入 doc 文件?
- dart - 我可以在子类中重新定义超类的属性吗?(可能是 c# 的新修饰符?)