programming4us
programming4us
DESKTOP

Use a Stopwatch to Profile Your Code

10/13/2010 5:15:13 PM
Use the System.Diagnostics.Stopwatch class.

While there are many extensive profiling packages out there (there is a profiler included in some editions of Visual Studio), sometimes you just need to time a known block of code with a stopwatch.

System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
Decimal total = 0;
int limit = 1000000;
for (int i = 0; i < limit; ++i)
{
total = total + (Decimal)Math.Sqrt(i);
}
timer.Stop();
Console.WriteLine("Sum of sqrts: {0}",total);
Console.WriteLine("Elapsed milliseconds: {0}",
timer.ElapsedMilliseconds);
Console.WriteLine("Elapsed time: {0}", timer.Elapsed);

This produces the output:

Sum of sqrts: 666666166.45882210823608
Elapsed milliseconds: 282
Elapsed time: 00:00:00.2828692

A useful trick when you need to use the Stopwatch for debugging purposes is to utilize the IDisposable interface to automate the use of the stopwatch:

class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable
{
public AutoStopwatch()
{
Start();
}

public void Dispose()
{
Stop();
Console.WriteLine("Elapsed: {0}", this.Elapsed);
}
}

Now you can take advantage of the using {} syntax:

using (new AutoStopwatch())
{
Decimal total2 = 0;
int limit2 = 1000000;
for (int i = 0; i < limit2; ++i)
{
total2 = total2 + (Decimal)Math.Sqrt(i);
}
}

Besides Start() and Stop(), there are also Reset(), which stops and sets Elapsed to 0, and Restart(), which sets Elapsed to 0, but lets timer continue running.

Other  
 
Video
PS4 game trailer XBox One game trailer
WiiU game trailer 3ds game trailer
Top 10 Video Game
-   Rise of Incarnates [PC] Zeus Trailer
-   Heroes Reborn | The Extraordinary Among Us (Preview)
-   Battleborn | E3 2015 Gameplay Demo
-   Fortnite [PC] Mac Showcase Trailer
-   Overwatch [PC] Zarya Gameplay Trailer
-   Tony Hawk's Pro Skater 5 [PS3/PS4/X360/XOne] THPS Is Back Trailer
-   Bombing Busters Trailer
-   Blade & Soul 'What is Blade & Soul?' Trailer
-   Cast of the Seven Godsends 'Plague Armour' Trailer
-   Guncraft X360 Trailer
-   Disgaea 5: Alliance of Vengeance | Official Trailer
-   XCOM 2 [PC] E3 2015 Gameplay Trailer
-   RONIN | Turn-Based Action Platformer
-   Balance Benny | Trailer
-   We Happy Few | An Uncle Jack Episode - Nighty Night, The Pied Piper of Hamlyn, Part1
Game of War | Kate Upton Commercial
programming4us
 
 
programming4us