Time elapse computation in milliseconds C# - c#

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?

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;

Answer EDITED based on comments
This answer is only trying to count the total elapsed Milliseconds between two times, where the times are derived directly from DateTime.Now. As per the conversation, it's understood that DateTime.Now is vulnerable to outside influences. Hence the best solution would be to use the Stopwatch class. Here's a link that better explains (IMO) and discusses the performance between DateTimeNow, DateTime.Ticks, StopWatch.
Original Answer
The way you cast it into a int is the issue. You need better casting and extra elements :)
This may looks simple compared to an efficient 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 reference on the web, you may want to check out as well.

You're looking for the Stopwatch class. It is specifically designed to bring back high-accuracy 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;

Stopwatch there are examples in the URL
https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stopwatch?view=netframework-4.8
using System.Diagnostics;
//...
Stopwatch watch = new Stopwatch();
watch.Start();
// here the complex program.
//...
watch.Stop();
TimeSpan timeSpan = watch.Elapsed;
Console.WriteLine("Time: {0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes,
timeSpan.Seconds, timeSpan.Milliseconds);

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.

This works for me:
var lapsedTime = DateTime.Now.Subtract(beginTime).TotalMilliseconds;

Here is what I used to obtain the time for a simple computation:
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));
}
}

Related

Method execution time not showing

Im trying to measure method execution time, but it didn't show the execution time. Can anyone help me to solve the problem?
public static int SequentialSearch(int[] point, int findPoint)
{
DateTime start = DateTime.Now;
int i;
for (i = 0; i < point.Length; i++)
{
if (findPoint== point[i])
{
return i;
}
}
DateTime end = DateTime.Now;
TimeSpan ts = (end - start);
Console.WriteLine("Elapsed Time is {0} ms", ts.TotalMilliseconds);
return -1;
}
There is actually a better way to do this, use StopWatch
//You need this using statement
using System.Diagnostics;
//Set it up, and then start it.
var timer = new Stopwatch();
timer.Start();
//Run your code
MethodToTime();
//Now stop the timer
timer.Stop();
//You can output either directly the elapsed MS
Console.WriteLine($"RunTime {timer.ElapsedMilliseconds}ms");
//Or you can get the elasped time span and output
TimeSpan ts = stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine("RunTime " + elapsedTime);

Running Timers in the Background c# Console

Wondering if there's a way to have a timer running in the background of a project that can be accessed if the user inputs a certain thing. At the moment this doesn't work
Timer t = new Timer(Program.TimerCallback, null, 0, 1000);
if (Console.ReadLine() == "i")
{
TimeSpan time = TimeSpan.FromSeconds(Program.seconds);
string str = time.ToString(#"mm\:ss");
Console.WriteLine("Time :" + str);
}
public static void TimerCallback(object o)
{
seconds +=1;
}
I used to have to code above within the Callback but then I couldn't do anything while it was running the timer. Thanks for any help
If I understand correctly, you don't actually need a timer:
DateTime startTime = DateTime.Now; // Just have a reference time
if (Console.ReadLine() == "i")
{
TimeSpan time = DateTime.Now - startTime; // Compute difference between "now" and "then"
string str = time.ToString(#"mm\:ss");
Console.WriteLine("Time :" + str);
}
should do the trick.
Subtracting two DateTimes like this gives you a TimeSpan: DateTime.Subtraction Operator
If you need better precision, you can make use of the StopWatch class, which also has a little more convenient API:
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
if (Console.ReadLine() == "i")
{
TimeSpan time = stopWatch.Elapsed;
string str = time.ToString(#"mm\:ss");
Console.WriteLine("Time :" + str);
}
BUT do not think you can do (micro-)benchmarks with this. If you intend to do so, consider Benchmark.NET (not affiliated).

How to implement clock() of c++ in c#?

I want to implement clock method in c# and get difference time of two clock as describe in below code. I use timers ,stopwatch and DateTime in c# but i didn't get correct time as i get in c++.
C++ code is describe below :
clock_t start_time, diff_time;
start_time = clock();
int i = 0;
for(i=0;i<10;i++)
{
.....
}
diff_time = clock();
diff_time -= start_time;
C# code is :
var start_time = Stopwatch.StartNew();
for (int i = 0; i <= 10; i++)
i++;
var diff_time = Stopwatch.StartNew();
var diff_times = (start_time.ElapsedTicks - diff_time.ElapsedTicks);
I think StopWatch should be used to measure code performance and other similar comparisons. If is the case, ok.
Or else, maybe you should consider DateTime.Now
The C function clock() returns a clock_t value that is the number of clock ticks elapsed since the program started. The number of seconds used by the CPU is obtained dividing this result by CLOCKS_PER_SEC.
For DateTime, check:
https://learn.microsoft.com/pt-br/dotnet/api/system.datetime?view=netframework-4.8
-> Some parts below:
The DateTime value type represents dates and times measured in 100-nanosecond units called ticks. Example: in the gregorian calendar a ticks value of 31241376000000000L represents the date Friday, January 01, 0100 12:00:00 midnight.
...
If you are working with a ticks value that you want to convert to some other time interval, such as minutes or seconds, you should use the TimeSpan.TicksPerDay, TimeSpan.TicksPerHour, TimeSpan.TicksPerMinute, TimeSpan.TicksPerSecond, or TimeSpan.TicksPerMillisecond constant to perform the conversion. For example, to add the number of seconds represented by a specified number of ticks to the Second component of a DateTime value, you can use the expression
dateValue.Second + nTicks/Timespan.TicksPerSecond.
...
Here is a simple implementation of the Clock() function in C#
static void Main(string[] args)
{
long CLOCKS_PER_SEC = 10000000;
long lngElapsedTime_t = Clock();
long lngElapsedTime;
int i, j, k, m;
for (i = 0; i < 5000000; i++)
{
j = i / 50;
k = j * 50;
m = i - k;
if (m == 1) { Console.WriteLine(i); }
}
lngElapsedTime = (Clock() - lngElapsedTime_t) / CLOCKS_PER_SEC;
Console.WriteLine("<<{0}>> The time in Ticks", lngElapsedTime_t);
Console.WriteLine("<<{0}>> The elapsed time in seconds", lngElapsedTime);
Console.ReadKey();
}
public static long Clock()
{
long clock_t = (long)DateTime.Now.Ticks;
return clock_t;
}

Time duration,time start and time end of a method in C#

how can I record the time duration, time start and time end of a method once it was executed using c#?
for example, I click a button and it will do something. Once it start, I'll get the start time, then when the execution is done, I'll get the time end and also the duration of time it take to finish.
You can use the Stopwatch, which resides in System.Diagnostics namespace.
This has the features of a normal stopwatch, with Start, Stop, Reset, ElapsedMilliseconds and so forth.
This is great for measuring a specific code block or method. You do however state that you want both start and end time in addition to the duration of execution. You could create a custom stopwatch by inheriting the Stopwatch class and extending it with a couple of DateTime properties.
public class CustomStopwatch : Stopwatch
{
public DateTime? StartAt { get; private set; }
public DateTime? EndAt { get; private set; }
public void Start()
{
StartAt = DateTime.Now;
base.Start();
}
public void Stop()
{
EndAt = DateTime.Now;
base.Stop();
}
public void Reset()
{
StartAt = null;
EndAt = null;
base.Reset();
}
public void Restart()
{
StartAt = DateTime.Now;
EndAt = null;
base.Restart();
}
}
And use it like this:
CustomStopwatch sw = new CustomStopwatch();
sw.Start();
Thread.Sleep(2342); // just to use some time, logic would be in here somewhere.
sw.Stop();
Console.WriteLine("Stopwatch elapsed: {0}, StartAt: {1}, EndAt: {2}", sw.ElapsedMilliseconds, sw.StartAt.Value, sw.EndAt.Value);
You can use System.Diagnostics.Stopwatch class to achieve this. see the sample
// Create new stopwatch
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
// Begin timing
stopwatch.Start();
// Tasks performed by method
// Stop timing
stopwatch.Stop();
Console.WriteLine("Time taken : {0}", stopwatch.Elapsed);
I've done it by doing this
var watch = System.Diagnostics.Stopwatch.StartNew();
string startTime = DateTime.Now.ToLongTimeString();
//Insert Code Here
watch.Stop();
string timeEnd = DateTime.Now.ToLongTimeString();
//Time Format
string[] hours = watch.Elapsed.TotalHours.ToString().Split('.');
string[] minutes = watch.Elapsed.TotalMinutes.ToString().Split('.');
string[] seconds = watch.Elapsed.TotalSeconds.ToString().Split('.');
string[] milliseconds = watch.Elapsed.TotalMilliseconds.ToString().Split('.');
MessageBox.Show(hours[0].ToString() + ":" + minutes[0].ToString() + ":" + seconds[0].ToString() + "." + milliseconds[0].ToString());
First, you need to create a stopwatch object.
private readonly Stopwatch stopwatch = new Stopwatch();
Then, your method:
public void MyMethod()
{
stopwatch.Start();
// Any other code here.
stopwatch.Stop();
//returns longs
long runningTimeInMs = stopwatch.ElapsedMilliseconds;
}

DateTime.AddDays or new DateTime

I'm creating a list of a month's worth of dates. I'm wondering what will be more efficient
List<DateTime> GetDates(DateTime StartDay) {
List<DateTime> dates = new List<DateTime>();
int TotalDays=StartDay.AddMonths(1).AddDays(-1).Day;
for (int i=1; i<TotalDays; i++) {
dates.Add(new DateTime(StartDay.Year, StartDay.Month, i));
}
return dates;
}
or
List<DateTime> GetDates(DateTime StartDay) {
List<DateTime> dates = new List<DateTime>();
DateTime NextMonth = StartDay.AddMonths(1);
for (DateTime curr=StartDay; !curr.Equals(NextMonth); curr=curr.AddDays(1)) {
dates.Add(curr);
}
return dates;
}
basically, is new DateTime() or DateTime.addDays more efficient.
UPDATE:
static void Main(string[] args) {
System.Diagnostics.Stopwatch sw=new System.Diagnostics.Stopwatch();
long t1, t2, total;
List<DateTime> l;
DateTime begin = DateTime.Now;
total = 0L;
for (int i=0; i<10; i++) {
sw.Start();
l = GetDates(begin);
sw.Stop();
sw.Stop();
t1 = sw.ElapsedTicks;
sw.Reset();
sw.Start();
l = GetDates2(begin);
sw.Stop();
t2=sw.ElapsedTicks;
total += t1- t2;
Console.WriteLine("Test {0} : {1} {2} : {3}", i,t1,t2, t1- t2);
}
Console.WriteLine("Total: {0}", total);
Console.WriteLine("\n\nDone");
Console.ReadLine();
}
static List<DateTime> GetDates(DateTime StartDay) {
List<DateTime> dates = new List<DateTime>();
int TotalDays=StartDay.AddMonths(10000).AddDays(-1).Day;
for (int i=1; i<TotalDays; i++) {
dates.Add(new DateTime(StartDay.Year, StartDay.Month, i));
}
return dates;
}
static List<DateTime> GetDates2(DateTime StartDay) {
List<DateTime> dates = new List<DateTime>();
DateTime NextMonth = StartDay.AddMonths(10000);
for (DateTime curr=StartDay; !curr.Equals(NextMonth); curr=curr.AddDays(1)) {
dates.Add(curr);
}
return dates;
}
Test 0 : 2203229 63086205 : -60882976
Test 1 : 63126483 102969090 : -39842607
Test 2 : 102991588 93487982 : 9503606
Test 3 : 93510942 69439034 : 24071908
Test 4 : 69465137 70660555 : -1195418
Test 5 : 70695702 68224849 : 2470853
Test 6 : 68248593 63555492 : 4693101
Test 7 : 63578536 65086357 : -1507821
Test 8 : 65108190 64035573 : 1072617
Test 9 : 64066128 64933449 : -867321
Total: -62484058
Done
results are consistently negative... way negative, so, looks like the constructor and integer test is the more efficient method.
Measure it - write a test program and see which one takes less time.
I believe datetime operations return new datetime structures so you will be creating new instances either way.
http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Unless you are doing some financial processing then I would worry more about readability than performance here. Only start worrying about performance somewhere like here if it's a proven bottleneck.
Since they both do the same thing in the end, there isn't much of a difference.
If you're looking for efficiency, just use ticks. All (that I've seen) calls in DateTime are eventually converted into ticks before any math gets done.
It's really hard to imagine a case in which this would make a significant difference, but Reflector shows that the AddDays technique should be more efficient.
Compare the core logic of AddDays (from Add(Double, Int32))
long num = (long) ((value * scale) + ((value >= 0.0) ? 0.5 : -0.5));
if ((num <= -315537897600000L) || (num >= 0x11efae44cb400L)) {
// Throw omitted
}
return this.AddTicks(num * 0x2710L);
To the core logic of the DateTime(int, int, int) constructor (from DateToTicks):
if (((year >= 1) && (year <= 0x270f)) && ((month >= 1) && (month <= 12)))
{
int[] numArray = IsLeapYear(year) ? DaysToMonth366 : DaysToMonth365;
if ((day >= 1) && (day <= (numArray[month] - numArray[month - 1])))
{
int num = year - 1;
int num2 = ((((((num * 0x16d) + (num / 4)) - (num / 100)) + (num / 400)) + numArray[month - 1]) + day) - 1;
return (num2 * 0xc92a69c000L);
}
}
// Throw omitted
AddDays just converts the specified number of days to the equivalent number of ticks (a long) and adds it to the existing ticks.
Creating a new DateTime using the year/month/day constructor requires many more calculations. That constructor has to check whether the specified year is a leap year, allocate an array of days in each month, perform a bunch of extra operations, just to finally get the number of ticks those three numbers represent.
Edit: DateTime.AddDays(int) is faster than new DateTime(int, int, int), but your first algorithm is faster than the second algorithm. This is probably because the iteration costs are much higher in the second algorithm. As you observed in your edit, this might well be because DateTime.Equals is more expensive than comparing integers.
Here is a working test program, with the algorithms implemented so that they can actually be compared (they still need work, though):
class Program
{
static void Main(string[] args)
{
IList<DateTime> l1, l2;
DateTime begin = new DateTime(2000, 1, 1);
Stopwatch timer1 = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
l1 = GetDates(begin);
timer1.Stop();
Stopwatch timer2 = Stopwatch.StartNew();
for (int i = 0; i < 10000; i++)
l2 = GetDates2(begin);
timer2.Stop();
Console.WriteLine("new DateTime: {0}\n.AddDays: {1}",
timer1.ElapsedTicks, timer2.ElapsedTicks);
Console.ReadLine();
}
static IList<DateTime> GetDates(DateTime StartDay)
{
IList<DateTime> dates = new List<DateTime>();
int TotalDays = DateTime.DaysInMonth(StartDay.Year, StartDay.Month);
for (int i = 0; i < TotalDays; i++)
dates.Add(new DateTime(StartDay.Year, StartDay.Month, i + 1));
return dates;
}
static IList<DateTime> GetDates2(DateTime StartDay)
{
IList<DateTime> dates = new List<DateTime>();
DateTime NextMonth = StartDay.AddMonths(1);
for (DateTime curr = StartDay; !curr.Equals(NextMonth); curr = curr.AddDays(1))
dates.Add(curr);
return dates;
}
} // class
Output (I added the commas):
new DateTime: 545,307,375
.AddDays: 180,071,512
These results seem pretty clear to me, though honestly I thought they'd be a lot closer.
I agree with Mark. Test both methods yourself and see which one is faster. Use the Stopwatch class to get accurate timings of how long each method takes to run. My first guess is that since both end up creating new structures anyway, that any speed difference will be negligible. Also, with only generating a month's worth of dates (31 days maximum), I don't think either method will be that much slower than the other. Perhaps is you you were generating thousands or millions of dates, it would make a difference, but for 31 dates, it's probably premature optimization.

Categories

Resources