Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

How To: Measure execution time in C#

Rate me:
Please Sign up or sign in to vote.
2.00/5 (1 vote)
26 Feb 2011CPOL 13.5K   1   3
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.

C#
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)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralReinventing the Stopwatch Class? Pin
Pavel Vladov11-Jul-12 22:02
Pavel Vladov11-Jul-12 22:02 
GeneralReason for my vote of 2 Reinvention of the Stopwatch class. Pin
JV99999-Mar-11 0:57
professionalJV99999-Mar-11 0:57 
GeneralThe Timer class you've listed is the Stopwatch class. The o... Pin
Andrew Rissing1-Mar-11 3:47
Andrew Rissing1-Mar-11 3:47 

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

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