drill
drill

Reputation: 115

Measure execution time of a thread in C#

In my application I am executing a new .NET Thread and within that thread I am acomplishing a task.

I am using Stopwatch to measure the execution time but Stopwatch measures the execution time of all threads of OS (nut just the execution time for my thread). I want a way to measure just the time that my created thread takes to execute its own instructions.

Is there such a way of measuring in .NET?

Upvotes: 8

Views: 10016

Answers (2)

Daniel Brückner
Daniel Brückner

Reputation: 59645

There is no way to do this in managed code only, but you can PInvoke QueryThreadCycleTime or GetThreadTimes. There is one thing to keep in mind - there is no requirement that there must be a one to one relationship between managed and native threads but as far as I know this is the way it currently works. Using Stopwatch you will always get the elapsed wall clock time including time when your thread was suspended.

Upvotes: 5

AgentFire
AgentFire

Reputation: 9780

This code measures the execution time of a thread:

void ThreadMethod() {
    Stopwatch sw = Stopwatch.StartNew();
    SomeActions();
    vat time = sw.Elapsed;
}

Run the method within your thread and you will get your execution time.

Upvotes: -1

Related Questions