TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to C-SHARP

C# Stopwatch Examples

Use the Stopwatch type from System.Diagnostics. Stopwatch performs benchmarks.
Stopwatch. This .NET type measures time elapsed. It is useful for micro-benchmarks in code optimization. It can perform routine and continuous performance monitoring.
The Stopwatch type, found in System.Diagnostics, is useful in many contexts. Stopwatch provides easy-to-use and accurate measurement of time elapsed. It helps with benchmarking.
An example. Stopwatch is ideal for timing any operation. The code includes the "System.Diagnostics" namespace at the top. This is where the Stopwatch class is defined in the Framework.

Start: The Start method tells the Stopwatch to store the current time. It queries Windows to find the current tick count of the system.

Stop: We call Stop on the instance Stopwatch. This tells the Stopwatch to capture the current tick count of the system.

Elapsed: The Elapsed property on Stopwatch is a TimeSpan struct, which overrides the ToString method.

TimeSpanToString
C# program that uses Stopwatch using System; using System.Diagnostics; using System.Threading; class Program { static void Main() { // Create new stopwatch. Stopwatch stopwatch = new Stopwatch(); // Begin timing. stopwatch.Start(); // Do something. for (int i = 0; i < 1000; i++) { Thread.Sleep(1); } // Stop timing. stopwatch.Stop(); // Write result. Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed); } } Output Time elapsed: 00:00:01.0001477
Hours, minutes, seconds. Stopwatch can handle short timings of only a few milliseconds. For longer timings, we want to display hours, minutes and seconds. Nanoseconds aren't important here.

Format: We use Elapsed with a format string. We must escape the ":" characters in the format string. We use hh, mm and ss.

Note: Thanks to Mike Keller for the suggestion. Nanoseconds are not helpful for timing long-running tasks.

C# program that uses hours, minutes, seconds output using System; using System.Diagnostics; class Program { static void Main() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // ... This takes 10 seconds to finish. for (int i = 0; i < 1000; i++) { System.Threading.Thread.Sleep(10); } // Stop. stopwatch.Stop(); // Write hours, minutes and seconds. Console.WriteLine("Time elapsed: {0:hh\\:mm\\:ss}", stopwatch.Elapsed); } } Output Time elapsed: 00:00:10
StartNew. For benchmarks or diagnostics code, you probably will prefer the StartNew method. This uses a creational design pattern to return a new instance from a static type method.

Info: This method is called to create a new instance of Stopwatch. We show the var syntax, which is a shorthand for the type declaration.

Var
C# program that uses StartNew class Program { static void Main() { // Create new stopwatch. var stopwatch = System.Diagnostics.Stopwatch.StartNew(); // Do something (omitted). // Stop timing. stopwatch.Stop(); // Write the results (omitted). } }
ElapsedTicks. This is internally a readonly signed System.Int64 value. When you capture ElapsedTicks, you have to manually do the calculations to convert the values to seconds.

Here: The example code first creates a new Stopwatch with StartNew, and then captures the ElapsedTicks long property twice.

Long

WriteLine: The values are printed to the screen. The Console.WriteLine here was the most expensive operation. It took 7081 ticks.

Note: The ElapsedTicks value from Stopwatch is not normally the same as the DateTime.Ticks value.

Note 2: Stopwatch ticks are far more accurate, when the IsHighResolution property is true. Otherwise, they are equivalent.

C# program that uses ElapsedTicks using System; using System.Diagnostics; class Program { static void Main() { // Create a new Stopwatch. var stopwatch = Stopwatch.StartNew(); // Capture the elapsed ticks and write them to the console. long ticks1 = stopwatch.ElapsedTicks; Console.WriteLine(ticks1); // Capture the ticks again. // ... This will be a larger value. long ticks2 = stopwatch.ElapsedTicks; Console.WriteLine(ticks2); } } Output 11 7092
Restart, Reset. Restart sets the timer information to zero. It then calls Start again on the Stopwatch, so you can time further statements. This is like calling Reset and Start.

Reset: Reset, meanwhile, only sets the timer information to zero. It does not call Start on the Stopwatch.

So: After Reset, we need to explicitly call Start. In this program, try replacing Restart with Reset.

C# program that uses Restart method using System; using System.Diagnostics; using System.Threading; class Program { static void Main() { Stopwatch stop = Stopwatch.StartNew(); Thread.Sleep(1000); stop.Restart(); Thread.Sleep(1000); Console.WriteLine(stop.ElapsedMilliseconds); } } Output 1000
Performance. Stopwatch usage has a performance impact. The Stopwatch class is slower than many operations. This applies when you are using Stopwatch for routine monitoring.

Result: Using a Stopwatch is more expensive than simple operations in the .NET Framework.

And: For this reason, Stopwatch itself can become a performance problem. We should not use it in production code in tight loops.

Context: For context, simple additions and multiplications require only a couple nanoseconds on most systems.

C# program that tests Stopwatch execution time using System; using System.Diagnostics; class Program { const int _max = 1000000; static void Main() { var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { var sw = Stopwatch.StartNew(); sw = null; } s1.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) / _max).ToString("0.00 ns")); Console.Read(); } } Output 600.64 ns
Properties. Stopwatch has some static properties and fields, including Frequency and IsHighResolution. These determine the configuration of Stopwatch, which depends on the system.

Frequency: This returns the number of ticks the Stopwatch uses per second. It is used to convert ElapsedTicks to a figure in seconds.

IsHighResolution: Tells whether the Stopwatch is using high resolution timing. Stopwatch isn't as useful when this is false.

Stopwatch properties: Stopwatch.Frequency: 14318180 Stopwatch.IsHighResolution: True Stopwatch.GetTimestamp: 174412139895
IsRunning. This is only useful if your code uses Stop or Reset in unpredictable ways. For most micro-benchmarks, it is not necessary. Using the simplest logic for Stopwatch is best.
A summary. Stopwatch is an incredibly useful class for performing diagnostics or benchmarks. It is simple and powerful. It can lead to higher quality software.DateTime
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf