测量螺纹运行时间

本文关键字:运行时间 测量 | 更新日期: 2023-09-27 18:19:54

public void Foo(IRB inR) {
    Stopwatch sw = new Stopwatch();
    sw.Start();
    System.Threading.Thread theThread = new System.Threading.Thread(delegate() {
            if (inR.Ready) {
                inR.ABC();
                while (!inR.Ready) { Thread.Sleep(100); }
            }
            mP.CP = false;
        });
    theThread.Name = "aaabbbccc";
    theThread.Start();
}

所以,我想使用秒表测量"线程"运行的时间。(实际上,我想测量从创建此线程到线程结束的时间。我已经把stopwatch.start((放在我想要的地方了。但是我应该把我的秒表.stop((放在哪里?谢谢。

测量螺纹运行时间

为什么不把秒表代码放在线程本身呢?例如:

public class ThreadTimer
{
    private readonly ThreadStart realWork;
    public ThreadTimer(ThreadStart realWork)
    {
        this.realWork = realWork;
    }
    public void TimeAndExecute()
    {
        Stopwatch stopwatch = Stopwatch.StartNew();
        try
        {
            realWork();
        }
        finally
        {
            stopwatch.Stop();
            // Log or whatever here
        }
    }
}

然后:

ThreadStart work = delegate() {
    if (inR.Ready) {
        inR.ABC();
        while (!inR.Ready) { Thread.Sleep(100); }
    }
    mP.CP = false;
};
ThreadTimer timer = new ThreadTimer(work);
Thread thread = new Thread(timer.TimeAndExecute);
thread.Start();

你能把它放在你的委托的末尾吗?
如果将秒表对象创建为函数的本地变量,则必须将后台线程与正在运行的线程联接。或者,您可以在函数外部创建它,让线程在不连接的情况下运行。

public void ConditionPlate(IRB inR)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    System.Threading.Thread theThread = new System.Threading.Thread(delegate()
    {
        if (inR.Ready)
        {
            inR.ABC();
            while (!inR.Ready) { Thread.Sleep(100); }
        }
        mP.CP = false;
        // ********************************
        // This will stop the stopwatch.
        // ********************************
        sw.Stop();
    });
    theThread.Name = "aaabbbccc";
    theThread.Start();
    // Wait for the thread to stop (necessary if 'sw' is created here, locally)
    theThread.Join();
    // gets time required for creation of thread to thread completion.
    var elapsed = sw.Elapsed;
}