c0D3l0g1c
c0D3l0g1c

Reputation: 3164

C# Application - Reduce CPU Usage

I have a multithreaded C# application, where the core logic sits in a Timer.Elapsed event handler. The event handler contains 2 for loops which executes a maximum of n * n = 5 * 5 = 25 times.

The application performs well on my PC. I ran VS 2010 Profiler against the application and CPU usage averages at 20%.

The company tester says that on his PC this jumps to between 50% and 100% on his PC. This is causing a performance issues for him.

Any help would be appreciated.

Upvotes: 6

Views: 25485

Answers (5)

Nav E
Nav E

Reputation: 11

Add Thread.Sleep(int); in the code to reduce cpu time. even just 30 milliseconds can save the juice of the processor.

Upvotes: 1

Hassan Rahman
Hassan Rahman

Reputation: 5213

May be your application runs multiple threads. I have same issue that runs multiple threads and in each thread there is continuous update which makes the application usage from 50% to 100%.

After investigating the issue, I have just introduced the delay in continuous loop of the thread (Thread(100)). This brings the application usage back to 1% to 3%.

Upvotes: 1

mayur kumar
mayur kumar

Reputation: 11

just add the Thread.Sleep(1); inside your for loop. this stabilize the CPU usage and restrict from using CPU at Maximum speed.

Upvotes: 1

Mike Dunlavey
Mike Dunlavey

Reputation: 40709

You're in wondering and guessing mode. Forget CPU percent. What pros do is find out why the program's spending time and if it's necessary.

What you could do is just run that code flat out in a long loop, and sample it. I use this method. Stack samples will land preferentially in the heavy branches of the call tree. Chances are you can lop off some of those heavy branches and get a nice speedup.

Upvotes: 3

Marc Gravell
Marc Gravell

Reputation: 1064204

  • run the timer event less frequently
  • do the work on a worker thread (so the UI is at least responsive)
  • do less work in the timer (or do it more efficiently)
  • get more CPU

I'm guessing you really mean the third bullet, but we can't answer that without knowing what the code is doing; but (random suggestions without any context):

  • look at any collection access to see if there is a place for a dictionary, hash-set, or similar
  • check if you are doing vast amounts of IO (in particular to a DB) which could be reduced
  • check if you are going lots of thread-switches via Invoke (or the UI's equivalent)

Upvotes: 7

Related Questions