Reputation: 3563
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);
}
}
Upvotes: 0
Views: 78
Reputation: 20935
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);
}
}
Upvotes: 2
Reputation: 35881
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);
Upvotes: 3