Jeroen1984
Jeroen1984

Reputation: 1686

Ten times Thread.Sleep(100) or a single Thread.Sleep(1000)?

Is there a difference (from performance perspective) between:

Thread.Sleep(10000);

and

for(int i=0; i<100; i++)
{
   Thread.Sleep(100);
}

Does the single call to Thread.Sleep(10000) also results in context switches within this 10 seconds (so the OS can see if it's done sleeping), or is this thread really not served for 10 seconds?

Upvotes: 2

Views: 1030

Answers (2)

rajansoft1
rajansoft1

Reputation: 1356

in any case second loop will take time because of following overheads

  1. Memory utilization for 10 different thread objects
  2. 10 different callbacks will be initiated once you call thread.sleep
  3. Overhead cost for running loop
  4. if we want to run the code on single thread so why do we want a loop if we don't have any break point even.

Upvotes: 1

Nikolay Kostov
Nikolay Kostov

Reputation: 16983

The second code (for loop) requires more process swaps and should be little slower than Thread.Sleep(10000);

Anyway you can use System.Diagnostics.Stopwatch class to determine the exact time for these two approaches. I believe the difference will be very very small.

Upvotes: 2

Related Questions