In VB6 I used GetTickCount() Windows API. Is there a fuction in c# that will allow me to measure the time it takes to execute a piece of code?
Printable View
In VB6 I used GetTickCount() Windows API. Is there a fuction in c# that will allow me to measure the time it takes to execute a piece of code?
In 2005/2008 use StopWatch. In 2002/2003 you can either write your own class that uses the QueryPerformanceCounter API or search Google and grab someone else's.
Found this and it works:
Code:/* Read the initial time. */
DateTime startTime = DateTime.Now;
/* Here's the code you're trying to measure */
/* Read the end time. */
DateTime stopTime = DateTime.Now;
/* Compute the duration between the initial and the end time. */
TimeSpan duration = stopTime - startTime;
this.Text = duration.TotalMilliseconds.ToString();
Fyi, while that works, it's horribly inaccurate compared to the System.Diagnostics.StopWatch or the QueryPerformance API.
Try something more like this:
csharp Code:
using System.Diagnostics; Stopwatch sw = new Stopwatch(); sw.Start(); //run the code to time sw.Stop(); MessageBox.Show(sw.ElapsedTime.ToString());
There are a few other fun ways to get the elapsed time with a Stopwatch... my Breakout game is currently using ElapsedMilliseconds for a frame limiter. Fun stuff.