C# StopWatch

C# StopWatch

Instance of stopwatch in [C#] or Vb.net can be used for calculating elapsed time or time taken be function. Let's calculate time required for execution of function or task.

c# StopWatch

[C#] StopWatch

[C#] example uses System.Diagnostics to get instance of StopWatch. We are starting stopwatch instance just before execution of function and stopping it after execution of function. Instance of stop watch returns TimeSpan. How to get Day's and Time from time span is explained here in C# TimeSpan.

using System;
using System.Text;
using System.Diagnostics;
namespace Csharp.Timer.Example
{
class Program
{
static void Main(string[] args)
{
Stopwatch swForLoop = new Stopwatch();
Stopwatch swBuilder = new Stopwatch();
StringBuilder sb = new StringBuilder("Count ");
string str = "Count ";
swForLoop.Start();
for (long i = 0; i <= 50000; i++)
{
str = str + " " + i.ToString();
}
Console.WriteLine(str);
swForLoop.Stop();
swBuilder.Start();
for (long i = 0; i <= 50000; i++)
{
sb.Append(" ");
sb.Append(i.ToString());
}
Console.WriteLine(sb.ToString());
swBuilder.Stop();
Console.WriteLine("Time required for String concatination is: {0}", swForLoop.Elapsed);
Console.WriteLine("Time required for String Builder is: {0}", swForLoop.Elapsed);
Console.ReadLine();
}
}
}

(Vb.Net) example of StopWatch

Imports System.Text
Imports System.Diagnostics
Namespace CSharp.Timer.Example
Class Program
Private Shared Sub Main(args As String())
Dim swForLoop As New Stopwatch()
Dim swBuilder As New Stopwatch()
Dim sb As New StringBuilder("Count ")
Dim str As String = "Count "
swForLoop.Start()
For i As Long = 0 To 50000
str = str & " " & i.ToString()
Next
Console.WriteLine(str)
swForLoop.[Stop]()
swBuilder.Start()
For i As Long = 0 To 50000
sb.Append(" ")
sb.Append(i.ToString())
Next
Console.WriteLine(sb.ToString())
swBuilder.[Stop]()
Console.WriteLine("Time required for String concatination is: {0}", swForLoop.Elapsed)
Console.WriteLine("Time required for String Builder is: {0}", swForLoop.Elapsed)
Console.ReadLine()
End Sub
End Class
End Namespace
Output
Time required for String concatination is: 00:00:19.8082808
Time required for String Builder is: 00:00:19.8082808

Tags:

C# foreach loopc# stringc# arraylistC# DateTime DifferenceC# XML XmlReaderC# Binary To StringC# Regular Expression Get Text Between BracketsC# For LoopReplace string in C#C# Break StatementC# while loop

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.