Search code examples
c#.nettimetimespanstopwatch

measure Time for two task


There are two task in my program ,I need to compute time for each task , I read about stopwatch and TimeSpan but I do not know which one must I use and how do that ,I want to measure time for each task in millisecond

for (int num = 2; num < 243; num++)
   {
     do something\\ compute time for first task
     do something\\ compute time for second task

    }

Solution

  • You can easily use Stopwatch for this

     Stopwatch watch = new Stopwatch();
    
      watch.Start();
    
      // do something
      watch.Stop();
    
      Console.WriteLine(watch.ElapsedMilliseconds);
      watch.Reset();
    
      watch.Start();
      // do something different
      ...