Alex Rivera | Logout

Time elapse computation in milliseconds C#

Asked 2012-11-27T17:34:30.097
51

I need to time the execution of a code sequence written in C#. Using DateTime.Now I get incorrect values for the millisecond field. For example:

 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 may I replace DateTime in order to obtain the actual value of the elapsed time?

Edit
Report

1 Answer

2

DateTime.Millisecond just returns the millisecond fraction of the second, from 0-999. You would need to take the rest of the datetime into consideration when doing timings.

However, you should look at using the StopWatch class for these kinds of performance timings.

answered 2012-11-27T17:37:44.360

Your Answer