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?
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.
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.
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
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With