Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

How To: Measure execution time in C#

, 26 Feb 2011
Rate this:
Please Sign up or sign in to vote.
Here is a useful generic class you can directly use in your project.public class Timer{ public static readonly bool IsHighPerformance; [DllImport("Kernel32.dll")] private static extern bool QueryPerformanceCounter(out long lpPerformanceCount); //Retrieves the current...
Here is a useful generic class you can directly use in your project.
 
public class Timer
{
    public static readonly bool IsHighPerformance;
 
    [DllImport("Kernel32.dll")]
    private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
    //Retrieves the current value of the high-resolution performance counter.

    [DllImport("Kernel32.dll")]
    private static extern bool QueryPerformanceFrequency(out long lpFrequency);
    //Retrieves the frequency of the high-resolution performance counter, if one exists.
    //The frequency cannot change while the system is running.

    private long m_startTime;
    private long m_stopTime;
    private static long m_freq;
 
    static Timer()
    {
        try
        {
            IsHighPerformance = QueryPerformanceFrequency(out m_freq);
        }
        catch (Exception)
        {
            IsHighPerformance = false;
        }
    }
 
    public Timer()
    {
        m_startTime = 0;
        m_stopTime = 0;
    }
 
    ///
    /// Start the timer
    ///
    public void Start()
    {
        // let the waiting threads do their work
        Thread.Sleep(0);
 
        if (IsHighPerformance)
        {
            QueryPerformanceCounter(out m_startTime);
        }
        else
        {
            m_startTime = DateTime.Now.Ticks;
        }
    }
 
    ///
    /// Stop the timer
    ///
    public void Stop()
    {
        if (IsHighPerformance)
        {
            QueryPerformanceCounter(out m_stopTime);
        }
        else
        {
            m_stopTime = DateTime.Now.Ticks;
        }
    }
 
    ///
    /// Returns the duration of the timer (in fraction of seconds)
    ///
    public double DurationSeconds
    {
        get
        {
            if (IsHighPerformance)
            {
                return (double)(m_stopTime - m_startTime) / (double)m_freq;
            }
            else
            {
                TimeSpan span = (new DateTime(m_stopTime)) - (new DateTime(m_startTime));
                return span.TotalSeconds;
            }
        }
    }
 
    public double DurationMilliseconds
    {
        get
        {
            if (IsHighPerformance)
            {
                return (double)(m_stopTime - m_startTime) / (double)m_freq;
            }
            else
            {
                TimeSpan span = (new DateTime(m_stopTime)) - (new DateTime(m_startTime));
                return span.TotalMilliseconds;
            }
        }
    }
}
 

//////demo
//static void Main() {
//Timer timer = new Timer();
//timer.Start();
// do something here
//timer.Stop();
//Console.WriteLine(timer.DurationSeconds);
//}

 
//////////the second class time of without using the system function
class Timing2
{
    TimeSpan startingTime;
    TimeSpan duration;
    
    public Timing2()
    {
        startingTime = new TimeSpan(0);
        duration = new TimeSpan(0);
    }
 
    public void StopTime()
    {
        duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(startingTime);
    }
 
    public void startTime()
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        startingTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
    }
 
    public TimeSpan Result()
    {
        return duration;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Member 7709321

United States United States
No Biography provided

Comments and Discussions

 
GeneralReinventing the Stopwatch Class? [modified] PinmemberPavel Vladov11-Jul-12 22:02 
GeneralReason for my vote of 2 Reinvention of the Stopwatch class. PinmemberJV99999-Mar-11 0:57 
GeneralThe Timer class you've listed is the Stopwatch class. The o... PinmemberAndrew Rissing1-Mar-11 3:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 27 Feb 2011
Article Copyright 2011 by Member 7709321
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid