计算运行程序的时间 [英] count time of running program

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

问题描述

我使用TimeSpan计算从程序开始到结束的时间

我使用此代码来计算时间,但是当我运行代码时显示的时间与运行时不同同样的代码又是什么错误?





I using the TimeSpan to count the time from the beginning of my program to the end
I use this code to count the time but when I running my code show time that is different when I run the same code again what is the error?


DateTime  startTime = DateTime.Now;

do somethings

DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime - startTime;

推荐答案

为什么使用DateTime.Now来执行此操作?



有一个 System.Diagnostics.Stopwatch 类对于这样的计时来说好多了。
Why are you using DateTime.Now to do this??

There is the System.Diagnostics.Stopwatch class that's a lot better for timing something like this.


正如Dave和VJ所说,你应该使用 System.Diagnostics.Stopwatch



性能计时的一般准则:

预先计算您将要使用的所有输入值,并将它们存储在简单结构(例如数组)中。 (因此排除了计算时间。)

运行几次(多次)测试并平均结果。

忽略第一次通过测试以便排除JIT执行时间。
As Dave and VJ indicated you should use System.Diagnostics.Stopwatch.

Some general guidelines for performance timing:
Pre-compute all of the input values you're going to use and store them in simple structures (e.g. arrays). (So that computation time is excluded.)
Run each of the tests several (many) times and average the results.
Ignore the first time through the tests in order to exclude JIT execution time.


检查一下 -



Check this -

var stopWatch = new Stopwatch();
stopWatch.Start();
//do somthing here
stopWatch.Stop();

 var ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);


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

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