tags:

views:

213

answers:

8

What I mean is...

get the time, run the code, get the time, compare the time and get the seconds out:

am I doing this right?

DateTime timestamp = DateTime.Now;
//...do the code...
DateTime endstamp = DateTime.Now;

string results = ((endstamp.ticks - timestamp.ticks)/10000000).ToString();
+6  A: 

No. Use the System.Diagnostics.Stopwatch class instead. DateTime.Now doesn't have the level of precision that you desire (although the DateTime struct is plenty precise, in and of itself).

Stopwatch watch = new Stopwatch();
watch.Start();
// do stuff
watch.Stop();
long ticks = watch.ElapsedTicks;
Anthony Pegram
any implementation sample?
shogun
@Ryan, added sample.
Anthony Pegram
Indeed, DateTime has plenty of *precision* but it does not have a commensurate level of *accuracy*. See http://blogs.msdn.com/b/ericlippert/archive/2010/04/08/precision-and-accuracy-of-datetime.aspx for some thoughts on that.
Eric Lippert
+13  A: 

You should use Stopwatch for this, for example:

var sw = Stopwatch.StartNew();
//...do the code...
sw.Stop();
var result = sw.ElapsedTicks; //ticks it took
//or less accurate/for bigger tasks, sw.ElapsedMilliseconds

Edited to include @Brian's improvement from comments.

Nick Craver
+1. A shortcut is: `var sw = Stopwatch.StartNew();` which just brings the first two lines together into one. Also, unless it takes a TINY amount of time, I prefer `sw.ElapsedMilliseconds` since it means more to me than ticks.
Brian Genisio
@Brian - I've used this 1000 times and *never* noticed `.StartNew()`, hats off sir.
Nick Craver
The StopWatch was also nicely blogged by [James Michael](http://geekswithblogs.net/BlackRabbitCoder/archive/2010/08/26/c.net-five-little-wonders-that-make-code-better-1-of.aspx) and publicised by [ScottGu](http://weblogs.asp.net/scottgu/archive/2010/08/29/august-29th-links-net-asp-net-iis-express-silverlight-windows-phone-7.aspx) a couple of weeks ago
slugster
A: 

A better idea is to use the System.Diagnostics.StopWatch class http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

Edgar Sánchez
A: 

It's probably ok, but note that there are several means for "the amount of time it took to run some code". What you've got there is wall clock time: the amount of time that passed in the world between the first and second calls to DateTime.Now (approximately). That will include time spent waiting on locks or disk access, time spent running other threads that don't contain your code, etc.

David Seiler
+1  A: 

Obviously arbitary processes executing on your machine will likely distort the result you get.
A Stopwatch is a good solution, as stated in MSDN:

The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. Use the Frequency and IsHighResolution fields to determine the precision and resolution of the Stopwatch timing implementation.

The Stopwatch class assists the manipulation of timing-related performance counters within managed code. Specifically, the Frequency field and GetTimestamp method can be used in place of the unmanaged Win32 APIs QueryPerformanceFrequency and QueryPerformanceCounter.

Oren A
A: 

That will inflate your times just slightly, but in general it works. You can also follow aspect-oriented principles and adopt something like log4net to get this funcationality without having to code it up everywhere.

Here is an article on it.

David Moye
+11  A: 

As many people have noted, the high-precision Stopwatch class is designed for answering the question "how long did this take?" whereas the DateTime class is designed for answering the question "when does Doctor Who start?" Use the right tool for the job.

However, there is more to the problem of correctly measuring elapsed time than simply getting the timer right. You've also got to make sure that you're measuring what you really want to measure. For example, consider:

// start the timer
M();
// stop the timer
// start another timer
M();
// stop the timer

Is there going to be a significant difference between the timings of the two calls? Possibly yes. Remember, the first time a method is called the jitter has to compile it from IL into machine code. That takes time. The first call to a method can be in some cases many times longer than every subsequent call put together.

So which measurement is "right"? The first measurement? The second? An average of them? It depends on what you are trying to optimize for. If you are optimizing for fast startup then you care very very much about the jit time. If you are optimizing for number of identical pages served per second on a warmed-up server then you don't care at all about jit time and should be designing your tests to not measure it. Make sure you are measuring the thing you are actually optimizing for.

Eric Lippert
+1  A: 

The suggestions given in previous answers will work for simple measurements. If you need something more advanced, you might want to use a profiler (there are commercial ones and free ones such as equatec).

M4N