Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you throttle a long-running command-line EXE to avoid pegging the CPU?

Tags:

c#

I have a command line EXE written in C#. It's log parser that grinds through several GB worth of log files every night.

It pegs the processor at 100% for quite a while. Not ideal.

How could I "throttle" the app? It can take as long as it wants, but I'd rather have it use less of the total CPU.

Is there some coding method or theory to make an EXE slow down and take less CPU? I can't do anything in the environment it runs (like change the process priority), so any changes have to be within the code of the app itself.

like image 220
Deane Avatar asked Nov 28 '22 19:11

Deane


2 Answers

Try this:

using System.Diagnostics;

Process myProc = Process.GetCurrentProcess();
myProc.PriorityClass = ProcessPriorityClass.BelowNormal;

If that isn't low enough, there is a ProcessPriorityClass.Idle

MSDN Link 1
MSDN Link 2

like image 165
St. John Johnson Avatar answered Dec 24 '22 10:12

St. John Johnson


You can set the priority of the threads using the Thread.Priority property.

Of course, if there's nothing else trying to run that will still use 100% CPU - but I guess in that case you don't mind so much.

Does your application create any other threads or use the thread pool? If it does, you'll probably want to make sure those threads have a reduced priority too.

EDIT: Setting the process's overall priority is probably a better solution in general, but I'll leave this one up as an alternative.

like image 28
Jon Skeet Avatar answered Dec 24 '22 11:12

Jon Skeet