Howto: C # Performance Test extended functions

Source: Internet
Author: User

ReadArticleIt reminds me of this. It may not have much practical significance, but it is indeed a good idea.
We usually use stopwatch for time statistics in this way.

 
Stopwatch watch = stopwatch. startnew (); For (INT I = 0; I <runs; I ++) {......} watch. Stop ();

In this way, the running time can be counted, but anyone who has used Python knows that python has its own battery. In fact, using an extension function can achieve this similar function (PS: in fact, the function is quite different, but the skin has already drawn a lot like it ).
First, demonstrate how to use IT (count the usage time of the method A. Run for 100 times)

 
Class program {static void main (string [] ARGs) {A = new A (); Action Act =. run; console. writeline (Act. profile (100); console. read () ;}} public class A {public void run () {for (INT I = 0; I <100000; I ++ );}}}

Use the extension method to implement this requirement, so you do not need to write stopwatch repeatedly.

Public static class functionhelper {public static string profile (this action func, int runs) {stopwatch watch = stopwatch. startnew (); For (INT I = 0; I <runs; I ++) {func ();} watch. stop (); float sec = watch. elapsedmilliseconds/1000.0f; float freq = runs/sec; return string. format ("execute runs: {0}; sec: {1}; freq", runs, // times of Operation sec, // run time freq // Average Run Time );}}

With this extension method, you can automatically call performance functions for certain methods.

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.