Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.7k views
in Technique[技术] by (71.8m points)

c++ - While loop using a lot of CPU time

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 learn how keylogger and GetAsyncKeyState() work here.

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.

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...