Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What is the most accurate way of timing a thread or a line of code in C# assuming the application is multithreaded?

Kind regards,

like image 764
SharePoint Newbie Avatar asked Oct 31 '08 07:10

SharePoint Newbie


People also ask

How to calculate time taken by a process in C++?

To calculate time taken by a process, we can use clock () function which is available time.h. We can call the clock function at the beginning and end of the code for which we measure time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time, like following.

How can I time my C++ code?

One easy way is to time your code to see how long it takes to run. C++11 comes with some functionality in the chrono library to do just that. However, using the chrono library is a bit arcane. The good news is that we can easily encapsulate all the timing functionality we need into a class that we can then use in our own programs. That’s it!

How to measure the time taken by a code?

If you want to measure the time taken by a certain piece of code for execution, you should generally use the steady_clock, which is a monotonic clock that is never adjusted by the system.

What is a primary thread in C++?

This thread is called primary or main thread. Along with this main thread, a process can create one or more threads to execute a portion of the code. Additionally, a program can use the ThreadPool class to execute code on worker threads that are managed by the CLR.


2 Answers

What exactly do you mean by "timing a thread"?

To just time (in wall time) how long something takes, use System.Diagnostics.Stopwatch. I don't believe there's anything to measure the processor time taken by a particular thread. Of course, profilers will help you a lot, but they also affect the timing of the program they're examining, which makes things trickier.

like image 144
Jon Skeet Avatar answered Oct 05 '22 23:10

Jon Skeet


If you need to accurately time operations in .NET, you want the Stopwatch class (which wraps the Windows QueryPerformanceCounter API). Check out this (Internet Archive) post for thread timing considerations.

like image 38
Mitch Wheat Avatar answered Oct 06 '22 01:10

Mitch Wheat