简体   繁体   English

在C#中测量线程的执行时间

[英]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. 在我的应用程序中,我正在执行一个新的.NET线程,在该线程中,我正在完成一项任务。

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). 我使用秒表来测量执行时间,但是秒表测量OS的所有线程的执行时间(坚果只是我的线程的执行时间)。 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? 在.NET中有这样的测量方法吗?

There is no way to do this in managed code only, but you can PInvoke QueryThreadCycleTime or GetThreadTimes . 在托管代码中无法执行此操作,但您可以使用PInvoke QueryThreadCycleTimeGetThreadTimes 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. 使用Stopwatch您将始终获得经过的挂钟时间,包括线程暂停的时间。

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. 在您的线程中运行该方法,您将获得执行时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM