如何计算c#中的执行时间 [英] How to calculate execution time in c#

查看:223
本文介绍了如何计算c#中的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用此代码计算我所知道的所有项目的执行时间

 var watch = Stopwatch.StartNew(); 
//你要测量的代码来这里
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

但我有

 private void pb1_MouseClick(object sender,MouseEventArgs e)
{.....
....我的示例代码}



和其他完成我工作的按钮如何计算从pb1_MouseClick到按钮工作结束的执行时间

解决方案

解决方案1错过了一个非常重要的方面:您需要从测量中排除JIT编译。请参阅: http://en.wikipedia.org/wiki/Just-in-time_compilation



这很容易做到:你需要开始时间测量你开始计时后调用中涉及的所有方法至少已经被调用过一次。例如,您可以将所有内容调用至少一次,然后才开始测量。



如果不这样做是一个非常常见的错误。


另一条建议:收集足够的统计数据。观察到的时间结果的统计分散可能会出乎意料地高,因为时间取决于很多随机因素。



-SA

  private   void  pb1_MouseClick( object  sender,MouseEventArgs e)
{
var watch = Stopwatch.StartNew();

....我的示例代码
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
MessageBox.Show(elapsedMs.ToString());
}





如果你想执行用户与界面上不同按钮交互所需的时间并停止进程完成后StopWatch然后将StopWatch声明为全局并在必要时结束。


How to calculate execution time of all my project I know using this code

var watch = Stopwatch.StartNew();
// the code that you want to measure comes here
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;

but I have

private void pb1_MouseClick(object sender, MouseEventArgs e)
       {   .....
         .... my sample code }


and other buttons to complete my work how can calculate execution time from pb1_MouseClick to the end of my work in buttons

解决方案

Solution 1 missed one very important aspect: you need to exclude JIT-compilation from measurement. Please see: http://en.wikipedia.org/wiki/Just-in-time_compilation.

This is easy to do: you need to start time measuring when all the methods involved in the call after you start timing have been already called before at least once. For example, you can call everything to be timed at least once, and only then start your measurements.

Failure to do so is a very common mistake.

Another advice: collect enough statistics. The observed statistical dispersion of timing result can be surprisingly high, as timing depends on a lot of random factors.

—SA


private void pb1_MouseClick(object sender, MouseEventArgs e)
        {   
var watch = Stopwatch.StartNew();

          .... my sample code 
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
MessageBox.Show(elapsedMs.ToString());
}



If you want to execute how long it takes the user to interact with different buttons on the interface and stop the StopWatch after a process is complete then declare the StopWatch as a global and end it when necessary.


这篇关于如何计算c#中的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆