Quantity of CPU time used by a thread

K

Ken Durden

Is there a way to measure or ask .NET to tell me what amount of time a
thread spent actually executing on the CPU?

For example, I may spawn a thread that spends 99.9% of its time
waiting for an event to be set, and then performs some action. If the
thread runs for 10 hours, how can I find out what amount of that time
was spent doing real execution.

For a simple example, I could measure this myself... For example, if I
just had a loop that waited for an event to be set I could put a high
performance timer everytime I got into the body of the loop and
increment a total time before going back into my wait mode.

However, if my code in turn calls lots of other functions which may
also block waiting on some asynchronous action this gets really
complicated and kinda infeasible if the other code is out of my
control.

Therefore, I was hoping for some magic API call that gives me this
info.

Any ideas?

Thanks,
-ken
 
J

Justin Rogers

The only highly accurate way is to use GetThreadTimes (a Win32 API call). I
seem to recall having to do a GetCurrentThread, DuplicateHandle on this, and
finally CloseHandle when you are done. It isn't nice. The other option is
to use the profiler interfaces, but I don't think they have a managed
equivalent for those either.
 
C

Chris LaJoie

You could continually check the System.Environment.TickCount (think thats
it). It might not be accurate though, because TickCount measures in
milliseconds. if all you're doing is checking a single variable to see if
it's true or not, it will likely take under 1 ms, and simply adding up the
results of all of the cycles in the loop would still leave you with 0. What
I do to make sure that my loops don't steal too much cpu time is make them
go to sleep for a second or 2 during a loop, especially if they're not
needed to react instantly to a change.

....
while(true) {
if(breakTheLoop) break;
System.Threading.Thread.Sleep(2000); // sleep for 2 seconds
}
....
 
K

Ken Durden

Justin,

If I can figure out all the interop stuff to use this in MC++ then it
should be perfect... Thanks!

-ken
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

CPU by thread 12
Thread 1
lock used in thread and by event 9
A Thread program that show wrong value 2
Sleep thread from Main thread 5
Thread question 5
What is maximum time thread can be run? 3
Is there a way ? 4

Top