7
votes

I have a multi-threaded application with (4) thread i want to know how much processing time spent in threads. I've created all these threads with ThreadPool

Thread1 doing job1
Thread2 doing job2
..
..

result would be:
Thread1 was running in 12 millisecond
Thread2 was running in 20 millisecond

I've actually download a web page in a job that each job is processing in one thread i want to know how much time it takes a web page is downloaded (without the affection of other threads context switch in calculated time

4

4 Answers

8
votes
5
votes

If you want to get the total time you would get from a stopwatch, there's the Stopwatch class:

Stopwatch sw = Stopwatch.StartNew();
// execute code
sw.Stop();
// read and report on sw.ElapsedMilliseconds

If you want to find out how much time the thread was actually executing code (and not waiting for I/O etc.) you can examine the ProcessThread.TotalProcessorTime property, by enumerating the threads of the Process object for your application.

Note that threads in the thread pool are not destroyed after use, but left in the pool for reuse, which means your total time for a thread includes everything it has done before your current workload.

2
votes

the WMI class Win32_Thared contains properties KernelModeTime and UserModeTime which will, if available, give you a count of 100ns units of actual execution.

But, from the documentation:

If this information is not available, a value of 0 (zero) should be used.

So this might be OS dependent (it is certainly populated here on Win7).

A query like: select * from win32_thread where ProcessHandle="x" will get the Win32_Thread instances for process id x (ignore the "handle" in the name). E.g., using PowerShell, looking at its own threads:

PS[64bit] > gwmi -Query "select * from win32_thread where ProcessHandle=""7064"""|
ft -AutoSize Handle,KernelModeTime,UserModeTime

Handle KernelModeTime UserModeTime
------ -------------- ------------
5548              218          312
6620                0            0
6112                0            0
7148                0           15
6888                0            0
7380                0            0
3992                0            0
8372                0            0
644                 0            0
1328                0           15

(And to confirm this is not elapsed time, the process start time is 16:44:50 2010-09-30.

-3
votes

Can not be done. The problem is that unless you block it (hard to do- makes little sense) threads can be inteeruupted. So, while it TAKES THread2 20ms to complete, you do not know how much of that it was active.

The negative side of what is called preemtive multitasking.