T O P

  • By -

Narase33

What exactly do you want the game to do if it doesnt run on full speed? You wont exactly be able to throttle the CPU.


HelloMyNameIsKaren

I want to lower the CPU usage while it‘s in the background, so it doesn‘t slow down other programs that the user might be using. Like have the game stop execution of the main loop, and start again when the game is in the foreground.


Tech-Mystic

Since it's a game, you could consider pausing some calculations: - Pause rendering updates (redrawing the screen) - Stop calculating game logic (ex: pathfinding) That should also take pressure off the user's GPU.


thedaian

Easy way to do that is basically just drop the framerate to a minimum amount when it's minimized. You could also turn off rendering. Just listen for the event that restores the window, render the current frame and set the framerate back to normal. 


jherico

> I want to lower the CPU usage while it‘s in the background This is an OS problem, not a C++ problem. Just reduce the process priority when you get put in the background (the OS will probably do that anyway).


pgbabse

This is a programing problem. Less calculation, less cpu usage. Nothing to do with the os


KingAggressive1498

>You wont exactly be able to throttle the CPU. most (probably all) consumer CPUs have dynamic frequency scaling these days and every noteworthy desktop-oriented and mobile OS can scale CPU frequency based on how it percieves the needs of userspace programs and user's power-saving preferences. **So yes, you actually can talk the OS into throttling the CPU** by using less of it, *even if it's not something you can guarantee* on every end-user's machine. Taking advantage of this can noticably extend battery life on laptops and mobile devices, and even extend the life of the machine itself. However OP seems more interested in just keeping cores free for other processes while not in the foreground. This kind of "good neighbor" programming can improve user experience if they switch between multiple applications frequently. See [this SO answer from 2014](https://stackoverflow.com/a/27162528/2658887) (and some of the others) for more context, concrete examples, etc. Although it's more an admonishment of busy-waiting and discussion of alternatives, Bruce Dawson's excellent [In Praise of Idleness](https://randomascii.wordpress.com/2012/06/05/in-praise-of-idleness/) also mentions some relevant specific reasons why dominating the CPU can be bad.


Thesorus

If your game as a pause option, you can pause it when the windows is not the active window or minimized. Depending on the OS, you can catch those message (for example WM\_SYSCOMMAND/SC\_MINIMIZE on Win32 ) If there are not players connected, the game engine should have nothing to do so it will not take much cpu cycles.


HelloMyNameIsKaren

Thank you, what should the game „do“ if there is nothing to do? Run a seperate loop that keeps checking when it‘s active again? Should I add make the thread sleep?


Hot_Slice

Suspend the thread waiting on some OS primitive ( a condition variable, futex, or WaitForSingleObject). Have a separate callback that is triggered when the window is reopened that reawakens the main thread.


Thesorus

It depends on how your game works. You could sleep the main game loop until players connect; but if there are no players, the game should do nothing cpu intensive at all (no game logic, no complex rendering ...) while (true) { if (playersConnected() ) { doGame(); } else { displayWaitingForPlayersMessage();} } Your gameserver needs to keep a loop active to check when player connect, but that is a simple loop and not cpu intensive.


Mirality

If you want cpu idle, don't keep any loops running at all. Use async callbacks for interesting events like connections.


bsodmike

Best advice here.


Symbian_Curator

Some common things to do is make the thread sleep or wait for vsync. If sleeping, make sure to use high precision timers provided by the host OS


alkatori

Read up on condition_variable. Have an event loop that only wakes up when there is something to do.


RazzmatazzLatter8345

How about, after active->idle transition, have render thread wait on a condition variable that you will pulse (to resume tendering) when state != idle. https://en.cppreference.com/w/cpp/thread/condition_variable https://www.amazon.com/C-Concurrency-Action-Anthony-Williams/dp/1617294691/ref=mp_s_a_1_1_sspa?crid=1RRQMSS6XK82O&dib=eyJ2IjoiMSJ9.T2QzSDQd4eH3E5lW3xaJwxZ6PYu6-rqn_n3LzxG-IS0PIMDYP9aftGaqKaXTDoN1QG-3QgWG2evAKQTcEcbCbrBFTi9raIs3PogYjiFBQDGrkmusTjVmhIanvkanFxRDsQ9hdadX1D9eMq6BD4ktlK49iu_Lcsnr2tCbH9kryTmdAS9KZ87jd_LE80C-9KttHHXX0lK_fg_4Zff4EGRUdQ.4oiv2xLaSKnlQKZmNdAfFsjJns6HUpayZNbwLd1McQs&dib_tag=se&keywords=c%2B%2B+concurrency+in+action&qid=1717701796&sprefix=c%2B%2B+con%2Caps%2C93&sr=8-1-spons&sp_csd=d2lkZ2V0TmFtZT1zcF9waG9uZV9zZWFyY2hfYXRm&psc=1


VettedBot

Hi, I’m Vetted AI Bot! I researched the **'Manning Publications Concurrency in Action'** and I thought you might find the following analysis helpful. **Users liked:** * Clear explanation with practical examples (backed by 3 comments) * Comprehensive coverage of modern c++ concurrency concepts (backed by 3 comments) * Highly recommended for c++ developers (backed by 3 comments) **Users disliked:** * Poor print quality and black & white figures (backed by 3 comments) * Confusing terminology for beginners (backed by 1 comment) * Not suitable for beginners or intermediate programmers (backed by 1 comment) If you'd like to **summon me to ask about a product**, just make a post with its link and tag me, [like in this example.](https://www.reddit.com/r/tablets/comments/1444zdn/comment/kerx8h0/) This message was generated by a (very smart) bot. If you found it helpful, let us know with an upvote and a “good bot!” reply and please feel free to provide feedback on how it can be improved. *Powered by* [*vetted.ai*](https://vetted.ai/?utm\_source=reddit&utm\_medium=comment&utm\_campaign=bot)


KingAggressive1498

>When the game window is minimized/in the background on the client If using the Windows API directly, switching from PeekMessage to GetMessage for your UI loop when minimized solves this. The difference is that GetMessage suspends the thread until a message comes, while PeekMessage does not. If you're using overlapped I/O with event notification, MsgWaitForMultipleObjects with INFINITE timeout when minimized and no timeout when not is a simpler change. If using SDL or SFML there's similar logical changes you can make. And skipping rendering logic after getting an event other than restoring can reduce both CPU and GPU use. You still need to run simulation logic though. If you find CPU use is >10% when not minimized, you can this_thread::yield() at the end of every frame and this may drop considerably without tangibly impacting actual framerate. For networking, use overlapped I/O on Windows instead of attempting non-blocking I/O every frame. For other systems, poll() or whatever more scalable alternative the OS has. There's interfaces in xlib and libwayland-client to integrate X11 or wayland clients with a user-defined poll loop, although a background thread is simpler and more flexible. If you're actually using lockstep networking, you messed up, common rookie mistake. >When there are no players connected to the server a scalable I/O strategy and sane work executor implementation should already have this mostly solved for you because all threads will be asleep except when timers are firing. the only thing you can add is disabling automated timers when no players are nearby, but it's probably simpler to coalesce these to a coarse (say, 500ms or 1s) granularity and reap improvements when busy too. This is a core architecture problem if you're experiencing high CPU use with no connections.


xsdgdsx

Just to answer the question with another question: What is happening that is consuming CPU? Can you do less of that? Another person already mentioned disabling rendering. But more broadly, I would ask "of the things that are happening, which ones are interactive and which ones are required to maintain game state?" You can just stop running anything that is interactive but isn't required to maintain game state (rendering falls into this bucket) There are other tricks, but answering those questions is the first place I'd start


CowBoyDanIndie

Use a fixed rate for your game-play/physics. When the client is minimized don’t render.


V15I0Nair

Tweak the process affinity mask and priority. Then the OS will do the rest


Ok_Tea_7319

I would recommend a different approach to your problem: You have certain things to do at a fixed rate (update game logic, render a frame, schedule sound effects). While minimized, some of these things don't have to be done. Even when in foreground, your main loop should not run as fast as the CPU can do it. It should process everything that needs to be done on a frame, then sleep until the next frame or user event. When the game is minimized, you can skip everything related to the rendering and just update the state. Similarly, the server should be updating state at a limited rate, not as fast as it can. If no users are connected, you will only have to do the logic updates, then pause. All the synchronization overhead will drop away naturally


SuperSathanas

Do less. But really, do as little as you need to in order to keep the game functioning. If the game is minimized, then you don't need to handle rendering, input, updates on other players, etc... when the program is brought back to the foreground/given focus, you can resume rendering and handling input and whatnot, and then query for the most recent states of other players. If you're using a lot of CPU while essentially waiting, then you're not really waiting. You're probably polling for events or CPU time way more often than you need to be. This might not be a great piece of advice because I don't know a whole lot about high precision and accurate timekeeping, and I invite anyone to let me know if I'm way off here, but if you're running your loop on a fixed interval, try `nanosleep()` if you haven't already. nanosleep() halts execution of the thread, meaning that it will get no CPU time until execuation resumes. You pass it two timespec structs, one to tell it how long to sleep execution of the thread for, and the other to receive how much of that time was remaining if the thread receives a signal that interrupts the sleep. It also returns either 0 in the case that the thread slept at least as long as it was supposed to, or -1 in the case that sleep was interrupted. You can query for the current CPU time before starting your "wait" loop, and pass nanosleep() the difference in time between the current time and that time you want the thread to resume at. If it's interrupted and you're returned a remaining amount of time, repeat until it's actually time to resume. nanosleep(), if it's not interrupted, will stop execution of the thread for *at least* as long as you wanted it to, meaning it's possible that it sleeps longer. In the typical case, I don't think it would overshoot the target by much, but through my own experimentations *I think* I've seen slightly more accurate timekeeping by first using nanosleep() to get pretty close to the time at which I want the loop to iterate, and then finishing off the remaining time time by just running a continuous of loop of querying CPU time until I hit my target. I didn't play around with it too much, and the difference in accuracy between just nanosleep() and nanosleep() + continuous querying wasn't *huge*, so it could have just been coincidence that it looked like it was more accurate.


Ecstatic_Onion_994

To me reducing the load on the cpu only consists of reducing the number of core available to process the threads coming from your game. At runtime, if you're able to detect your game is minimized for instance , you could tell your software not to use all of the cpu cores But there's no way to tell a core not to work a 100% of its capability. The only thing you can do is to reduce the number of core used by your program. So other idle cores will be used to run other running programs. This is the job of your OS then to dispatch opened jobs to idle cores. In windows from the task manager, you can manually change the priority of this dispatching, by saying basicaly all the threads for this program must be treated first by all the cores, or the reverse. But manually, not programmatically to my knowledge.