Using the. NET Stopwatch class to analyze your code

Source: Internet
Author: User

When we debug, optimize our code, want to know the actual execution time of a piece of code, or we suspect that a piece of code, or a few pieces of code execution is relatively slow,

Need to get specific execution time for a particular piece of code. There is a very useful class stopwatch.

The Stopwatch class is under the System.Diagnostics namespace. Basic tools that you can use to analyze. NET code blocks.

For example:

System.Diagnostics.Stopwatch timerobj = new System.Diagnostics.Stopwatch () Timerobj.start ();D ecimal Totaldec = 0;int Limit = 1000000;for (int i = 0; i < limit; ++i) {Totaldec = Totaldec + (Decimal) math.sqrt (i);} Timerobj.stop (); Console.WriteLine ("Sum of square Roots: {0}", Totaldec); Console.WriteLine ("Milliseconds elapsed: {0}", timerobj.elapsedmilliseconds); Console.WriteLine ("Time elapsed: {0}", timerobj.elapsed);

Output Result:
Sum of Square roots:666666166.45882210823608
Milliseconds elapsed:282
Time elapsed:00:00:00.2828692

When you use stopwatch to debug your time, you can use the IDisposable interface to automatically switch off stopwatch
1. Define a custom Stopwatch class that inherits System.Diagnostics.Stopwatch and IDisposable

Class AutoStopwatchDemo:System.Diagnostics.Stopwatch, Idisposable{public Autostopwatchdemo () {Start ();} public void Dispose () {Stop (); Console.WriteLine ("Elapsed: {0}", this. Elapsed);}}

2. Use in the code block you want to debug

using (new Autostopwatchdemo ()) {Decimal TotalObj2 = 0;int limitObj2 = 1000000;for (int i = 0; i < limit2; ++i) {Totalobj 2 = LimitObj2 + (Decimal) math.sqrt (i);}}

In addition, stopwatch has the start () and Stop () methods, and the Reset () method

Using the. NET Stopwatch class to analyze your code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.