While循环占用大量CPU时间 [英] While loop using a lot of CPU time

查看:373
本文介绍了While循环占用大量CPU时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的个人兴趣创建一个击键记录器,同时也想知道如何捕获和使用它们作为功能(例如按键快捷键)。

I am creating a keystroke logger for my personal interest, as well wanting to know how to capture and use them as functions (like key shortcuts).

此处。。

我让它在Code :: Blocks下运行,但最奇怪的是,当我检查任务管理器时,我的CPU使用率上升到100%。当我关闭程序时,它会下降,当我重新打开它时,它会上升到100%。

I got it to run under Code::Blocks, but the weirdest things is that when I check my task manager, my CPU Usage rises to 100%. When I close the program, it goes back down, and goes back up to 100% when I turn it back on.

我认为这是因为无限的while循环不断检查输入,但是我想知道是否有任何方法可以减少CPU使用率而又不会失去功能。

I presume it's because of the infinite while loop constantly checking for inputs, but I want to know if there's any way to decrease the CPU usage without losing function.

PS我将如何制作一个快捷键?例如,按 Ctrl + E 可使程序退出。

P.S How would I make a key shortcut? For example, pressing Ctrl+E to make the program exit.

推荐答案

您的程序实际上耗尽了它的所有CPU时间,因为它永远没有理由停止执行-当它到达循环的结尾时,它将立即再次开始,并且没有理由延迟其在循环体内的任何处理

Your program essentially eats up whatever CPU time it can because it never has a reason to stop executing - when it hits the end of the loop it immediately begins again, and there's no reason to delay in any of its processing within the loop body.

大多数应用程序不会持续轮询键盘的状态,而是监听操作系统广播的键盘事件。在侦听事件时,您的程序无需消耗CPU时间,因此可以休眠直到事件发生为止,从而释放处理器以供使用。

Most applications don't continuously poll the state of the keyboard, but instead listen for keyboard events broadcast by the OS. While listening for an event, your program has no need to consume CPU time and thus will sleep until an event occurs, freeing the processor for usage until then.

(通常,这是一个例外,因为它们通常会轮询键盘状态。但是,它们通常会限制执行此操作的频率(通常最多一帧一次),因此CPU使用率仍然受到限制。)

(Games are often an exception to this, in that they'll often poll the keyboard state. However, they typically limit how often they do this - usually to once a frame at most - and thus the CPU usage is still bounded.)

这篇关于While循环占用大量CPU时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆