Reputation: 1729
I have found several articles (including some questions in SA), trying to find the cost of basic operations.
However, i tried to make my own little program, so that i could test it myself. When trying to test addition and subtraction i encountered something, that i present you in simple code
int a,i,j;
DateTime d1,d2;
a = 0;
d1= DateTime.Now;
for (i = 1; i <= 10000; i++)
for (j = 1; j <= 10000; j++)
a = a + 1;
d2=DateTime.Now;
Console.WriteLine("a=a+1\t1E8\t"+(d2-d1));
a = 0;
d1 = DateTime.Now;
for (i = 1; i <= 10000; i++)
for (j = 1; j <= 10000; j++)
a = a + 1;
d2 = DateTime.Now;
Console.WriteLine("a=a+1\t1E8\t" + (d2 - d1));
a = 0;
d1 = DateTime.Now;
for (i = 1; i <= 10000; i++)
for (j = 1; j <= 10000; j++)
a = a + 1;
d2 = DateTime.Now;
Console.WriteLine("a=a+1\t1E8\t" + (d2 - d1));
a = 0;
d1 = DateTime.Now;
for (i = 1; i <= 10000; i++)
for (j = 1; j <= 10000; j++)
a = a + 1;
d2 = DateTime.Now;
Console.WriteLine("a=a+1\t1E8\t" + (d2 - d1));
Console.ReadKey();
First i declare some variables and then i perform the same task 4 times. every single time i do the exact same thing. Always , the result is the following:
a=a+1 1E8 00:00:00.2300230
a=a+1 1E8 00:00:00.2180218
a=a+1 1E8 00:00:00.2130213
a=a+1 1E8 00:00:00.2150215
or
a=a+1 1E8 00:00:00.2340000
a=a+1 1E8 00:00:00.2170000
a=a+1 1E8 00:00:00.2130000
a=a+1 1E8 00:00:00.2100000
meaning that the first time, it ALWAYS takes longer to compute (about 5% longer). All the other times, the time is about the same.
Then i just add the line a=0;
after the first a=0;
. The result is as follows:
a=a+1 1E8 00:00:00.2210000
a=a+1 1E8 00:00:00.2170000
a=a+1 1E8 00:00:00.2200000
a=a+1 1E8 00:00:00.2170000
or even
a=a+1 1E8 00:00:00.2160000
a=a+1 1E8 00:00:00.2160000
a=a+1 1E8 00:00:00.2200000
a=a+1 1E8 00:00:00.2230000
So 3 questions:
Datetime
Personal POV: Something needs to be initialized when the program starts running. By adding an extra command (a=0), i give the program the time to make its initializations.
Flaw in POV:
When i change the number of loops from 10^8 to 10^9, the difference between time1 and time2 should again be ~0.015s(if my POV was valid). but now it is again ~0.15s (meaning again ~5%). If i add the second a=0
, then again time1~time2~time3~time4
Upvotes: 2
Views: 156
Reputation: 2254
Answer to your question number 3 -
Is there any better way to compute time interval than Datetime?
Use System.Diagnostics.Stopwatch for measuring time difference as it gives very high accuracy.
Upvotes: 3