How to calculate the code execution time in C#

2 Answers

0 votes
using System;

class Program
{
    static void Main() {
        var watch = System.Diagnostics.Stopwatch.StartNew();

        long sum = 0;       
        for (long i = 0; i < 9387391; i++) {
            sum += i;
        }
        
        watch.Stop();
        
        Console.WriteLine(sum);
        
        Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
    }
}




/*
run:
  
44061550199745
Execution Time: 9 ms
  
*/

 



answered Aug 12, 2021 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        var watch = System.Diagnostics.Stopwatch.StartNew();

        long sum = 0;       
        for (long i = 0; i < 9387391; i++) {
            sum += i;
        }
        
        watch.Stop();
        
        Console.WriteLine(sum);
        
        Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
        
        if (!watch.IsRunning)
            watch.Restart(); 
            
        sum = 0;
        for (long i = 0; i < 9000292008; i++) {
            sum += i;
        }
        
        watch.Stop();
        
        Console.WriteLine(sum);
        
        Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
    }
}




/*
run:
  
44061550199745
Execution Time: 23 ms
3609139962715086796
Execution Time: 9271 ms
  
*/

 



answered Aug 12, 2021 by avibootz

Related questions

1 answer 153 views
153 views asked Sep 26, 2021 by avibootz
3 answers 225 views
1 answer 314 views
2 answers 268 views
2 answers 292 views
1 answer 257 views
1 answer 224 views
...