How to make my program consume less CPU without disrupting its execution?
I have a program that reads the memory of a computer process continuously (with the while (true)
), but this ends up requiring a lot of CPU, reaching 20% used, my question is, how to decrease CPU usage without losing performance in the program?
Tried Thread.Sleep(10)
, it worked, CPU usage dropped to 1%, but even being only 10 thousandths, program performance dropped dramatically.
while (Vars.GlowActive) //Essa variavel sempre vai ser true
if (Vars.GlowAlways || Vars.GetKeyState(Vars.GlowButton) == 0)
{
for (int num = 1; num < 24; num++)
{
int entity = mem.Read<int>(Vars.bClient + Vars.EntList + (num * 0x10));
ehealth = mem.Read<int>(entity + Vars.Health);
int Glow = mem.Read<int>(entity + Vars.GlowIndex);
int EntTeam = mem.Read<int>(entity + Vars.Team);
if (EntTeam == Vars.MyTeam)
{
if (Vars.glowteamenabled)
{
if (Vars.TeamRainbow)
TeamColor();
color[0] = Vars.glow_team_r / 255;
color[1] = Vars.glow_team_g / 255;
color[2] = Vars.glow_team_b / 255;
DrawGlow(Glow, color);
}
}
else
{
if (Vars.glowenemyenabled)
{
if (Vars.EnemyRainbow)
EnemyColor();
else if (Vars.glowhealth)
{
Vars.glow_enemy_r = 255 - 2.55f * ehealth;
Vars.glow_enemy_g = 2.55f * ehealth;
Vars.glow_enemy_b = 0;
}
color[0] = Vars.glow_enemy_r / 255;
color[1] = Vars.glow_enemy_g / 255;
color[2] = Vars.glow_enemy_b / 255;
DrawGlow(Glow, color);
}
}
}
}
else if (one && Vars.BeepEnable)
{
Console.Beep(3000, 200);
one = !one;
}
}
Summary:
mem.Read
reads the memory of a process.
DrawGlow()
write in memory.
3 answers
Try decreasing sleep duration
Thread.Sleep(1);
Or use a Timer
var timer = new System.Timers.Timer();
timer.Interval = 10;
timer.Elapsed += (ctx, arg) => /*chama a sua funcao aqui*/;
timer.AutoReset = true;
timer.Start();
Not everything, not anything
A program that runs non-stop consumes more CPU. A program that sleeps always loses performance. How about doing both, but not always?
while ( Vars.GlowActive )
{
if ( Vars.GlowAlways || Vars.GetKeyState( Vars.GlowButton ) == 0 )
{
for ( int num = 1 ; num < 24 ; num++ ) // Ver observação
{
}
// Já que teve uma execuçao válida, não cairia no elseif abaixo
// então explicitamente tenta executar de novo
continue;
}
else if ( one && Vars.BeepEnable )
{
Console.Beep( 3000 , 200 );
one = !one;
}
// Se chegou aqui, não tinha dados a processar.
// Dar uma folga a espera de novos dados.
System.Threading.Thread.Yield();
}
Note
- this number 24 looks kind of magical. See if it's API requirement you're using. But if it's just an attempt to balance load between rounds and beeps, the best thing would be to take that
for
, and move the beep test into while.
Decrease the amount of Ifs in your program, from what I've seen you can use an and in some if's, this should improve a bit.