简体   繁体   English

算法性能C#

[英]algorithm performance c#

I want to measure the performance of my code.. if I consider the time as a criterion I have this code 我想衡量我的代码的性能..如果我以时间为标准,则我有此代码

DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Milliseconds ;

Question1: is this the only way that I can test the performance of my algorithm ? 问题1:这是我测试算法性能的唯一方法吗? Question2: what are other criterion that C# provide to test the performance? 问题2:C#还提供了哪些其他标准来测试性能? Regards 问候

use Stopwatch class 使用秒表

//Start a stopwatch: //启动秒表:

var watch = Stopwatch.StartNew();

//Execute the code //执行代码

watch.Stop(); //This stops the watch

The elapsed time can be measured by using Elapsed, ElapsedMilliSeconds and ElapsedTicks properties. 可以通过使用Elapsed,ElapsedMilliSeconds和ElapsedTicks属性来测量经过时间。

Try using the StopWatch class. 尝试使用StopWatch类。 It has significantly higher resolution than the DateTime and TimeSpan classes. 它具有比DateTime和TimeSpan类更高的分辨率。

Additionally, you can look at the Windows Performance Counters as a way of measuring performance while your application is running so that you can monitor the health of your application. 此外,您可以将Windows性能计数器视为一种在应用程序运行时评估性能的方法,以便可以监视应用程序的运行状况。

You can use a profiler (tool based, for example with SlimTune ) or measure the time with System.Diagnostics.Stopwatch . 您可以使用探查器(例如基于工具的SlimTune )或通过System.Diagnostics.Stopwatch测量时间 It has better precision than the DateTime hack. 它具有比DateTime hack更好的精度。

If you truly want to use DateTime (because it's easier to use), use UtcNow instead of Now . 如果您确实要使用DateTime (因为它更易于使用),请使用UtcNow而不是Now It's a little faster (because current date and time are stored in UTC format in Windows) and as an added bonus, you can test your program around the DST change time :-). 速度稍快一些(因为当前日期和时间在Windows中以UTC格式存储),此外,您可以在DST更改时间附近测试程序:-)。

But yeah, use Stopwatch . 但是,是的,请使用Stopwatch

Stopwatch watch = Stopwatch.StartNew();
watch.Stop()

Ah... very important... your code is wrong 啊...非常重要...您的代码有误

ts.TotalMilliseconds

I did the same error yesterday, but I was measuring times around the second, so it was more difficult to notice :-) 昨天我也犯了同样的错误,但是我正在测量第二次的时间,所以更难发现:-)

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

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