Measuring performance in any multitasking system is difficult, it is especially difficult in .NET because your thread can be paused for garbage collection at any time. Dan Appleman suggests using UserProcessorTime to measure performance, this timer keeps track of how much time the thread spends in non-privileged execution.
TimeSpan tsStart; TimeSpan tsDuration; GC.Collect(); GC.WaitForPendingFinalizers(); tsStart = Process.GetCurrentProcess().Threads[0].UserProcessorTime; //Do stuff tsDuration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(tsStart); -----Original Message----- From: Mads Houmann [mailto:[EMAIL PROTECTED]] Sent: 11 April 2002 19:02 To: [EMAIL PROTECTED] Subject: Re: [DOTNET] Measuring performance If you don't mind calling out to Win32 you can use the PerformanceCounter APIs like this: using System; using System.Threading; using System.Runtime.InteropServices; using System.Security; [SuppressUnmanagedCodeSecurity] public sealed class StopWatch { private long startTime = 0; private long stopTime = 0; public void Start() { stopTime = 0; QueryPerformanceCounter(ref startTime); } public void Stop() { QueryPerformanceCounter(ref stopTime); } public long GetElapsedTicks() { if (stopTime == 0) return 0; return stopTime - startTime; } public double GetElapsedSeconds() { if (stopTime == 0) return 0.0; long frequency = 0; QueryPerformanceFrequency(ref frequency); return (stopTime - startTime) / (double) frequency; } [DllImport("kernel32")] private static extern bool QueryPerformanceCounter(ref long lpPerformanceCount); [DllImport("kernel32")] private static extern bool QueryPerformanceFrequency(ref long lpFrequency); } ----- Original Message ----- From: "Mattias Konradsson" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]> Sent: Wednesday, April 10, 2002 5:58 AM Subject: [DOTNET] Measuring performance > I want to be able to measure how many milliseconds/seconds a method takes to > execute (and print it right on the page, not store it elsewhere), I hazard a > guess > that it's possible with performance counters but I haven't been able to find > the relevant code, can anyone shove me in the right direction? > > Best regards > ---- > Mattias Konradsson > "Reinventing the wheel since 1977" > > You can read messages from the DOTNET archive, unsubscribe from DOTNET, or > subscribe to other DevelopMentor lists at http://discuss.develop.com. You can read messages from the DOTNET archive, unsubscribe from DOTNET, or subscribe to other DevelopMentor lists at http://discuss.develop.com. You can read messages from the DOTNET archive, unsubscribe from DOTNET, or subscribe to other DevelopMentor lists at http://discuss.develop.com.