开发者

algorithm performance c#

开发者 https://www.devze.com 2023-02-10 06:58 出处:网络
I want to measure the performance of my code.. if I consider the time as a criterion I have this code

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 ? Question2: what are other criterion that C# provide to test the per开发者_如何学运维formance? Regards


Its always better to use System.Diagnostics.Stopwatch

Check this link for more details. Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch


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.


Try using the StopWatch class. It has significantly higher resolution than the DateTime and TimeSpan classes.

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.


You can use a profiler (tool based, for example with SlimTune) or measure the time with System.Diagnostics.Stopwatch. It has better precision than the DateTime hack.


If you truly want to use DateTime (because it's easier to use), use UtcNow instead of 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 :-).

But yeah, use 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 :-)

0

精彩评论

暂无评论...
验证码 换一张
取 消