Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you measure code block (thread) execution time with multiple concurrent threads in .NET

Right now we just use something like this

        stopWatch.Start();            
        try
        {
            method();
        }
        finally
        {
            stopWatch.Stop();
        }

Which works fine for synchronous methods, but some are executing asynchronously, so the time is skewed when multiple threads are executing. Is there an equivalent to System.Diagnostics.Stopwatch that will measure only time spend in the current thread?

We want to collect data over an extended period of time in our internal beta(alpha?) release, and running under a profiler full time isn't a feasible option.

Edit: To clarify, we want to only measure the time spent executing method(), so if Method1() and Method2() both start at the same time and Method1 finishes at the 2 second mark and Method2 finishes at the 4 second mark, I want something that would tell me that Method1 spent about 1 second executing and Method2 spend about 3 seconds executing (Assuming during the first 2 seconds they shared the (assumed single core) processor equally.

like image 508
Davy8 Avatar asked Dec 17 '08 16:12

Davy8


2 Answers

Hmm, from Jon Skeet's answer to this question:

Timing a line of code accurately in a threaded application, C#

And also this article:

http://lyon-smith.org/blogs/code-o-rama/archive/2007/07/17/timing-code-on-windows-with-the-rdtsc-instruction.aspx

It seems like there's no simple way to do this.

like image 51
Davy8 Avatar answered Oct 05 '22 00:10

Davy8


The stopwatch should measure time spent only in one thread. You would need to run a separate instance on every thread. This would give you probably the closes results to what you want.

Alternatively (preferred option if you want to monitor the whole application, and not just some methods), there are various performance counters you can use out of the box (they are updated by .Net runtime). There is lots of information on the web, you can start with msdn: http://msdn.microsoft.com/en-us/library/w8f5kw2e(VS.71).aspx

like image 28
Grzenio Avatar answered Oct 05 '22 01:10

Grzenio