While loop using a lot of CPU time

后端 未结 3 1612
無奈伤痛
無奈伤痛 2020-12-21 13:00

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).

I got the code to l

3条回答
  •  半阙折子戏
    2020-12-21 13:31

    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.

    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.

    (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.)

提交回复
热议问题