Vahid.m
Vahid.m

Reputation: 185

How long does my code take to run?

How can I find out how much time my C# code takes to run?

Upvotes: 11

Views: 8094

Answers (6)

Mike Dunlavey
Mike Dunlavey

Reputation: 40649

If you want simple, just put an N-iteration loop around it and use StopWatch (or just a wristwatch) and divide by N. For example, if you want microseconds, let N = 1000000. If you're worried about the overhead of the loop, just unroll it by a factor of 10.

Upvotes: 0

Tim Booker
Tim Booker

Reputation: 2789

I recommend using a profiling tool such as ANTS to test the speed of your application and find slow code. This will allow you to do a line-by-line test of execution times.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499770

As others have said, the Stopwatch class is good for the simple timing side of things. Other bits to bear in mind though:

  • Your code may generate objects which will need to be garbage collected after you've stopped the stopwatch
  • Conversely your timing may include other objects being garbage collected even if they have nothing to do with your code
  • If you start timing before you run your method for the first time, it will include JIT time
  • If you take a very short time, that leads to very unpredictable results - for benchmarking I tend to prefer running code for many seconds, to account for the app being interrupted by other processes etc.

If you're interested in benchmarking, I have the MiniBench project which I must get round to working on again at some point - it's not quite where I want it to end up, but it's a start. I talk more about what I want to achieve with it in this blog post.

Upvotes: 8

Fredrik Mörk
Fredrik Mörk

Reputation: 158289

Check out the Stopwatch class:

Stopwatch sw = new Stopwatch();
sw.Start();

// your code here

sw.Stop();
TimeSpan elapsedTime = sw.Elapsed;

Upvotes: 15

Noldorin
Noldorin

Reputation: 147240

The Stopwatch class offers high-precision timing in .NET. It is capable of measuring time with sensitivity of around 100s of nanoseconds (fractions of milliseconds). To get the exact resolution, read the value of Stopwatch.Frequency.

var timer = System.Diagnostics.Stopwatch.StartNew();
// Run code here.
var elapsed = timer.ElapsedMilliseconds.

Also, be sure to run your code repeatedly (as many times as is feasible) to get a better average time, as well as to reduce the effects of fluctuations in CPU load.

Upvotes: 14

Andy Gaskell
Andy Gaskell

Reputation: 31761

Check out the Stopwatch class.

Upvotes: 1

Related Questions