Quantcast
Channel: Control-F5 - C#
Viewing all articles
Browse latest Browse all 13

Performance Monitoring in C#

$
0
0

Here is one of simplest ways you can monitor your code execution times in C#.


Nothing fancy, create a class and name it.. well I can't find a cool name for it so: 

publicclass PerfMonitor{private Stopwatch watch;public PerfMonitor(){
            watch =new Stopwatch();}publicvoid StartCount(){
            watch.Reset();
            watch.Start();}publicstring GetTimeElapsed(){return watch.Elapsed.ToString();}publicstring GetFinalElapsed(){string elapsed = watch.Elapsed.ToString();
            watch.Stop();return elapsed;}}

This is basically a wrapper over Stopwatch.

Now you could use this anywhere to see for example: 

  • various sensible parts of a system where you are working and know that performance is an issue
  • correct parts of system that make a lot of server or database connections, and use this to see initial and later results

Example in a business app:

class SeriousBusiness{publicstaticvoid Main(){
            PerfMonitor perfMonitor =new PerfMonitor();

            perfMonitor.StartCount();
            DoSomeNastyBusiness();
            Console.WriteLine("DoSomeNastyBusiness method took :"+
                Environment.NewLine + perfMonitor.GetFinalElapsed());//After developer makes it pretty
            perfMonitor.StartCount();
            DoSomePrettyBusiness();
            Console.WriteLine("DoSomePrettyBusiness method took :"+
                Environment.NewLine + perfMonitor.GetFinalElapsed());

            Console.ReadKey();}privatestaticvoid DoSomeNastyBusiness(){// simulate load
            Thread.Sleep(1500);}privatestaticvoid DoSomePrettyBusiness(){
            Thread.Sleep(500);}}


Hit Control-F5:


If you like this or can suggest other ways to do this leave this in comments or email me at: 

alexandrudanpop@gmail.com


Cheers,

Alex


Viewing all articles
Browse latest Browse all 13

Trending Articles