experimental snippet for less cpu usage if it's not needed

Posted By: Kartoffel

experimental snippet for less cpu usage if it's not needed - 03/03/17 17:45

Here's an experimental code snippet (global while-loop) that's supposed minimize acknex's CPU-usage if it's not needed.
However, for this to work you have to use a global while loop and execute everything from there ( which is probably not the way you're used to do things smirk ).

Also, note that I'm not even sure if this works properly.

Code:
#include <acknex.h>
#include <windows.h>

//

void main()
{
	fps_max = 60;
	
	//
	
	double dTms = 0.0; // delta time (milliseconds)
	
	dtimer();
	wait(1);
	
	while(1)
	{
		proc_mode = PROC_LATE;
		
		dTms += dtimer() / 1000.0; // dTms = last frame's elapsed time in milliseconds
		
		//////////
		
		
		
		
		//// do EVERYTHING from here
		
		
		
		
		//////////
		
		double dTms_busy = dtimer() / 1000.0; // time 
		dTms = dTms_busy;
		
		int SleepTime = floor(1000.0 / fps_max - dTms_busy - 2.0); // remaining time in milliseconds (rounded down, minus 2 for safety)
		
		if(SleepTime > floor(1000.0 / fps_max) - 2) // limit max. sleep time
			SleepTime = floor(1000.0 / fps_max) - 2;
		
		if(SleepTime > 0) // use window's Sleep() function if necessary
			Sleep(SleepTime);
		
		//
		
		wait(1);
	}
}


I read somewhere that acknex's frame timer syncs up the program with the screen refreshrate by "wasting" cpu cycles until the end of the frame is reached and the program can continue.
this has no impact on how fast the program runs since it only does that after all the code for that specific frame is executed but it's still an unecessary way of keeping the cpu usage up.

in the code above I'm using dtimer() to measure the actual execution time of the instructions (within one frame) and calculate the remaining time until the next frame can start.
then I'm using window's Sleep() function to get closer to the end of the frame so acknex's internal timer has less time to wait (should be around 1-3 milliseconds).
Posted By: Reconnoiter

Re: experimental snippet for less cpu usage if it's not needed - 03/03/17 21:13

Interesting. What I currently do for a project is limiting fps_max (to e.g. 10) after some idle time and/or no acknex is not the top window. On my laptop this reduces cpu usage in the task manager from ~35% to 3% (and estimated battery time from ~1.5 to ~3.5).
© 2024 lite-C Forums