0

What is the best way to time how long a program runs for? I have a code and need to find out how long it will run. It seems to me that the best way - is to start a timer.

using System;
using System.Collections.Generic;

class MainClass
{
    static void Main()
    {
        var x = new {MyEnumerator = new List<int>() { 1, 2, 3 }.GetEnumerator()};
        while (x.MyEnumerator.MoveNext())
            Console.WriteLine(x.MyEnumerator.Current);
    }
}
Southpaw Hare
  • 1,535
  • 3
  • 24
  • 50
Amazing User
  • 3,473
  • 10
  • 36
  • 75
  • 2
    If you mean, how long did it run, use a Stopwatch. – Peter Ritchie Feb 14 '14 at 22:35
  • 1
    Have you ever looked at [`Stopwatch`](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx) class? From documentation; _Provides a set of methods and properties that you can use to accurately measure elapsed time_ – Soner Gönül Feb 14 '14 at 22:35
  • 1
    @PeterRitchie Be careful, Peter. You neither camelCased nor hyperlinked the word "Stopwatch" - not everyone knows what that is! – Southpaw Hare Feb 14 '14 at 22:37
  • possible duplicate of [Measuring code execution time](http://stackoverflow.com/questions/16376191/measuring-code-execution-time) – Soner Gönül Feb 14 '14 at 22:39
  • 1
    Keep in mind that you should time your code multiple times (e.g. in a for loop or similar construct) and take the average or fastest time or whatever you'd like. For instance, the first time a method is called might take significantly longer than subsequent calls. – itsme86 Feb 14 '14 at 22:50
  • @SouthpawHare Stopwatch *is* camel cased, stopwatch is a one word. I know of only one Stopwatch in the .NET framework. – Peter Ritchie Feb 14 '14 at 23:13

2 Answers2

3

Use a Stopwatch to see how long code took to run:

    var sw = Stopwatch.StartNew();
    var x = new {MyEnumerator = new List<int>() { 1, 2, 3 }.GetEnumerator()};
    while (x.MyEnumerator.MoveNext())
        Console.WriteLine(x.MyEnumerator.Current);
    Debug.WriteLine(sw.Elapsed);
Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
2

Here's 1 way of doing it. With the Stopwatch class.

using System;
using System.Diagnostics;
using System.Threading;

class MainClass
{
    static void Main()
    {
    // Create new stopwatch
    Stopwatch stopwatch = new Stopwatch();

    // Begin timing
    stopwatch.Start();

    // Do something    
    var x = new {MyEnumerator = new List<int>() { 1, 2, 3 }.GetEnumerator()};
    while (x.MyEnumerator.MoveNext())
        Console.WriteLine(x.MyEnumerator.Current);

    // Stop timing
    stopwatch.Stop();

    // Write result
    Console.WriteLine("Time elapsed: {0}",
        stopwatch.Elapsed);
    }
}
Shiva
  • 20,575
  • 14
  • 82
  • 112