Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time elapse computation in milliseconds C#

Tags:

c#

time

timer

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?

like image 794
Sebi Avatar asked Nov 27 '12 17:11

Sebi


People also ask

How to get device clock timer in milliseconds in C++?

Time Library (time.h) has a clock method to get timer of your device clock in milliseconds. This library can be used in both C & C++ applications. There is a very simple clock example in official dockwiki here. Let’s look at this example, As you see here we use time.h library and clock_t datatype to define start and end of timing.

How to calculate time taken by a process in C++?

To calculate time taken by a process, we can use clock () function which is available time.h. We can call the clock function at the beginning and end of the code for which we measure time, subtract the values, and then divide by CLOCKS_PER_SEC (the number of clock ticks per second) to get processor time, like following.

How to get millisecond fraction of the second in datetime?

DateTime.Millisecondjust 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 StopWatchclass for these kinds of performance timings. Share Improve this answer Follow answered Nov 27 '12 at 17:37


1 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; 
like image 77
RavingDev Avatar answered Oct 16 '22 22:10

RavingDev