C # millisecond time calculation

I need runtime code written in C #. Using DateTime.Now I get the wrong values ​​for the millisecond field. For instance:

int start_time, elapsed_time; start_time = DateTime.Now.Millisecond; for(int i = 0; i < N_ITER; i++) { // cpu intensive sequence } elapsed_time = DateTime.Now.Millisecond - start_time; 

elapsed_time gives negative values.

How can I replace DateTime to get the actual elapsed time value?

+17
source share
6 answers
 using System.Diagnostics; //... var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < N_ITER; i++) { // cpu intensive sequence } stopwatch.Stop(); elapsed_time = stopwatch.ElapsedMilliseconds; 
+63
source

Reply EDIT based on comments

This answer only tries to calculate the total number of elapsed milliseconds between two points where the time is obtained directly from DateTime.Now . As for the conversation, he realized that DateTime.Now is vulnerable to external influences. Therefore, the best solution would be to use the Stopwatch class. Here's a link that better explains (IMO) and discusses performance between DateTimeNow, DateTime.Ticks, StopWatch .

Original answer

The question is how do you convert it to int. You need better casting and additional elements :) It may look simple compared to an effective timer. But it works:

 DateTime startTime, endTime; startTime = DateTime.Now; //do your work endTime = DateTime.Now; Double elapsedMillisecs = ((TimeSpan)(endTime - startTime)).TotalMilliseconds; 

There is a link on the Internet that you can also check.

+9
source

You are looking for the Stopwatch class. It is specifically designed to return high-precision time measurements.

 var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i = 0; i < N_ITER; i++) { // cpu intensive sequence } stopwatch.Stop(); var elapsed = stopwatch.ElapsedMilliseconds; 
+3
source

DateTime.Millisecond returns the millisecond fraction of a second, starting from 0-999. When doing timings, you will need to consider the rest of the time.

However, you should study the StopWatch class for such performance time slots.

+2
source

Here is what I used to get the time for a simple calculation:

 class Program { static void Main(string[] args) { Decimal p = 0.00001m; Decimal i = 0m; DateTime start = new DateTime(); DateTime stop = new DateTime(); for (i = p; i <= 5; i = i + p) { Console.WriteLine("result is: " + i); if (i==p) start = DateTime.Now; if (i==5) stop = DateTime.Now; } Console.WriteLine("Time to compute: " + (stop-start)); } } 
+1
source

This works for me:

 var lapsedTime = DateTime.Now.Subtract(beginTime).TotalMilliseconds; 
0
source

All Articles