views:

251

answers:

4

Joe Duffy states in the MSDN article "Using concurrency for scalability" that the cost of creating a thread is approximately 200,000 cycles, and the cost of destroying is about 100,000 cycles.

When I try to create a new thread to perform some calculations, I would like to be sure that the calculations themselves are more expensive than 200,000 cycles.

How could I measure the CPU cycles? I think it would be more interesting than measuring the execution time.

+1  A: 

I would check out the System.Diagnostic namespace. It has a lot of stuff on tracking memory and cpu usage.

Jeremy Reagan
A: 

I asked a closely related question a couple of days ago, and have yet not found a way to measure the actual CPU cycle usage of the code: http://stackoverflow.com/questions/234411/limiting-assembly-execution-number-of-cpu-cycles

In your case, could you not run a profiling of the calculation and see how much time a single calculation takes, and compare that to the aggregate time of spawning a thread that does the calculation and then kill the thread off afterwards?

Mark S. Rasmussen
+2  A: 

You could use a sampling profiler like Intel's Vtune to obtain a measure of how many CPU cycles are being consumed with a minimum amount of disturbance on the system being measured.

When using threads however the goal is to avoid needless spawning new threads. Look into using the thread pool. This will let you run work items asynchronously, but without having to spawn a new thread for each item.

Rob Walker
mod +1 for the thread pool advice!
Dave Markle
The thread pool just pools existing thread; if a thread is not still created the creation costs are the same as I wouldn't use any thread pools.
Michael Damatov
Yes, thread creation costs the same if you do it or the thread pool does. But the thread pool helps to avoid unnecessary creation by keeping some number of idle threads around. If your work items are small enough to want to avoid the creation costs they sound like a good fit for a threadpool.
Rob Walker
A: 

Here's the problem with counting CPU cycles. Different CPUs take differing numbers of cycles to implement the same instruction. So it's not too reliable a metric IMO. I think what you should be measuring is time to execute, and in .NET, you use System.Environment.TickCount to accomplish this. I think that's the best you've got...

Dave Markle