Question

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);
    }
}
Was it helpful?

Solution

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);

OTHER TIPS

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top