c# For loop getting faster with Console.Writeline afterwards - c#

I wrote a test program to see how much faster different kind of loops with pointers are and encountered a strange behaviuor where if i add a Console.WriteLine("1: " + sum) after the first loop some of the loops get faster and another becomes slower.
So how does this affect the perfomance of the loop because it seems like it does not interact with the loops at all.
My example code has the line which affects loop perfomance commented out to show the normal performance and if I uncomment it the speed changes.
class Program
{
static void Main(string[] args)
{
Class1 c = new Class1();
c.Do();
}
}
public class Class1
{
public unsafe int n = 1000000000;
public unsafe int[] arr;
public Class1 ()
{
arr = new int[n];
for (int i = 0; i < arr.Length; i++)
{
arr[i] = 2;
}
}
public void Do ()
{
int sum = 1;
Stopwatch sw = new Stopwatch();
sw.Start();
sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
sw.Stop();
//Console.WriteLine("1: " + sum);
Console.WriteLine("1: " + sw.ElapsedMilliseconds);
unsafe
{
sw.Reset();
sw.Start();
sum = 0;
for (int i = 0; i < arr.Length; i++)
{
sum += arr[i];
}
sw.Stop();
Console.WriteLine("2: " + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
sum = 0;
fixed (int* start = arr)
{
for (int i = 0; i < arr.Length; i++)
{
sum += *(start + i);
}
}
sw.Stop();
Console.WriteLine("3: " + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
sum = 0;
fixed (int* start = arr)
{
int* iter = start;
var remaining = arr.Length;
while (remaining-- > 0)
{
sum += *iter;
iter++;
}
}
sw.Stop();
Console.WriteLine("4: " + sw.ElapsedMilliseconds);
sw.Reset();
sw.Start();
sum = 0;
fixed (int* start = arr)
{
int* end = start + n;
int* iter = start - 1;
while (iter++ < end)
{
sum += *iter;
}
}
sw.Stop();
Console.WriteLine("5: " + sw.ElapsedMilliseconds);
}
}
}
output:
1: 2082
2: 2038
3: 1800
4: 2061
5: 1724
output with uncommented line:
1: 2000000000
1: 1949
2: 1953
3: 1998
4: 2055
5: 1724
I tested it multiple times to see if it was just a random difference but it seems to be consistent.

Related

Storing values in an array and outputting the highest,lowest,average. Output flaw

This was a small problem the teacher gave us at school. We were asked to make a program which keeps asking the user to input test scores until he inputs -99 to stop the program. The values are stored in an array and the highest, lowest and average scores are displayed.
The problem I have with my code is that whenever I run it it always gives me a value of 0 for lowest scores even though there are no zeros in the input. Can anyone please point out the mistake in my code?
Code:
static void Main(string[] args)
{
int[] za = new int[100];
scores(za, 0);
}
public static void scores(int[] ar, int x)
{
Console.Write("Please enter homework score [0 to 100] (-99 to exit): ");
int a = Convert.ToInt16(Console.ReadLine());
if (a != -99)
{
ar[x] = a;
x++;
scores(ar, x);
}
else
{
Console.Clear();
Console.WriteLine("Homework App");
int[] arr = new int[x];
foreach (int l in arr)
{
arr[l] = ar[l];
}
int lowest = arr[0];
for (int i = 1; i < arr.Length; i++)
{
if (lowest > arr[i]) { lowest = arr[i]; }
}
int highest = arr[0];
for (int j = 1; j < arr.Length; j++)
{
if (highest < arr[j]) { highest = arr[j]; }
}
double sum = 0;
double nums = 0;
for (int k = 0; k < arr.Length; k++)
{
sum = sum + arr[k];
nums++;
}
double average = sum / nums;
Console.WriteLine("Highest Score: {0}", highest);
Console.WriteLine("Lowest Score: {0}", lowest);
Console.WriteLine("Average Score: {0}", average);
Console.ReadLine();
}
}
When you're copying items, don't use a foreach loop and then the element stored in the array as the index that you're inserting to. Instead, use a for loop with a counter variable.
You should change this:
int[] arr = new int[x];
foreach (int l in arr)
{
// You're using the wrong value for the index here.
// l represents the value of the item stored in `arr`, which is `0`
arr[l] = ar[l];
}
To this:
int[] arr = new int[x];
for (var counter = 0; counter < x; counter++)
{
arr[counter] = ar[counter];
}

method inline still slower than manually refactor (merge) into same method?

I used to think if a method is inlined, then theoretically it is identical to the merge of the method and the calling method, but the benchmark showed there is slightly difference in performance
e.g. this takes 100ms
public long TestA()
{
long ret = 0;
for (int n = 0; n < testSize; n++)
{
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
{
ret += myArray[i][j];
}
}
return ret;
}
this takes 110ms (if I force MethodImplOptions.NoInlining on GetIt then it will be 400ms, so I assume it is auto inlined)
public long TestB()
{
long ret = 0;
for (int n = 0; n < testSize; n++)
{
for (int i = 0; i < a; i++)
for (int j = 0; j < b; j++)
{
ret += GetIt(i, j);
}
}
return ret;
}
int GetIt(int x, int y)
{
return myArray[x][y];
}
OK, I attach a snippet of benchmark function i used
public static void RunTests(Func<long> myTest)
{
const int numTrials = 100;
Stopwatch sw = new Stopwatch();
double[] sample = new double[numTrials];
Console.WriteLine("Checksum is {0:N0}", myTest());
sw.Start();
myTest();
sw.Stop();
Console.WriteLine("Estimated time per test is {0:N0} ticks\n", sw.ElapsedTicks);
if (sw.ElapsedTicks < 100)
{
Console.WriteLine("Ticks per test is less than 100 ticks. Suggest increase testSize.");
return;
}
if (sw.ElapsedTicks > 10000)
{
Console.WriteLine("Ticks per test is more than 10,000 ticks. Suggest decrease testSize.");
return;
}
for (int i = 0; i < numTrials / 3; i++)
{
myTest();
}
string testName = myTest.Method.Name;
Console.WriteLine("----> Starting benchmark {0}\n", myTest.Method.Name);
for (int i = 0; i < numTrials; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
sw.Restart();
myTest();
sw.Stop();
sample[i] = sw.ElapsedTicks;
}
double testResult = DataSetAnalysis.Report(sample);
DataSetAnalysis.ConsistencyAnalyze(sample, 0.1);
Console.WriteLine();
for (int j = 0; j < numTrials; j = j + 5)
Console.WriteLine("{0,8:N0} {1,8:N0} {2,8:N0} {3,8:N0} {4,8:N0}", sample[j], sample[j + 1], sample[j + 2], sample[j + 3], sample[j + 4]);
Console.WriteLine("\n----> End of benchmark");
}
The resulting number of IL instructions differs slightly, the maxstack differs significantly:
TestA:
// Code size 78 (0x4e)
.maxstack 2
TestB:
// Code size 88 (0x58)
.maxstack 4
GetIt:
// Code size 7 (0x7)
.maxstack 1
C# does inline at JIT, so whether inline or not IL doesn't change.
MethodImplOptions.NoInlining is not the same as inline keyword in F#

Adding a single Console.WriteLine() outside a loop changes a loop's timings - why?

Consider the following code:
using System;
using System.Diagnostics;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
for (int trial = 0; trial < 4; ++trial)
{
sw.Restart();
loop1();
Console.WriteLine("loop1() took " + sw.Elapsed);
sw.Restart();
loop2();
Console.WriteLine("loop2() took " + sw.Elapsed);
sw.Restart();
loop3();
Console.WriteLine("loop3() took " + sw.Elapsed);
// Console.WriteLine(); // <-- Uncomment this and the timings change a LOT!
}
}
static void loop1()
{
bool done = false;
for (int i = 0; i < 100000 && !done; ++i)
{
for (int j = 0; j < 100000 && !done; ++j)
{
for (int k = 0; k < 2; ++k)
{
if (i == 9900)
{
done = true;
break;
}
}
}
}
}
static void loop2()
{
for (int i = 0; i < 100000; ++i)
{
for (int j = 0; j < 100000; ++j)
{
for (int k = 0; k < 2; ++k)
{
if (i == 9900)
{
goto exit;
}
}
}
}
exit: return;
}
static void loop3()
{
for (int i = 0; i < 100000; ++i)
{
for (int j = 0; j < 100000; ++j)
{
for (int k = 0; k < 2; ++k)
{
if (i == 9900)
{
k = 2;
j = 100000;
i = 100000;
}
}
}
}
}
}
}
When I compile and run a RELEASE x86 build of this on Windows 7 x64 using Visual Studio 2010, I get the following timings (running on Intel Core i7)
loop1() took 00:00:01.7935267
loop2() took 00:00:01.4747297
loop3() took 00:00:05.6677592
loop1() took 00:00:01.7654008
loop2() took 00:00:01.4818888
loop3() took 00:00:05.7656440
loop1() took 00:00:01.7990239
loop2() took 00:00:01.5019258
loop3() took 00:00:05.7979425
loop1() took 00:00:01.8356245
loop2() took 00:00:01.5688070
loop3() took 00:00:05.7238753
That in itself is odd - why would loop3() be so much slower than the other loops?
Anyway, I then uncomment the indicated line (the Console.WriteLine()), and my timings become:
loop1() took 00:00:01.8229538
loop2() took 00:00:07.8174210
loop3() took 00:00:01.4879274
loop1() took 00:00:01.7691919
loop2() took 00:00:07.4781999
loop3() took 00:00:01.4810248
loop1() took 00:00:01.7749845
loop2() took 00:00:07.5304738
loop3() took 00:00:01.4634904
loop1() took 00:00:01.7521282
loop2() took 00:00:07.6325186
loop3() took 00:00:01.4663219
Now loop2() is far slower, and loop3() far quicker. I find this most curious...
So I have two questions:
Can anyone else reproduce this, and
If so, can anyone explain it?
[EDIT] I should add that I can verify these timings with a stopwatch, and I am running the test program from the command-line (so we can rule out Visual Studio interfering with it).
ADDENDUM:
I modified the program as follows to exclude the possibility that the JITTER is optimizing out the loops:
using System;
using System.Diagnostics;
using System.Text;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(test());
}
static string test()
{
Stopwatch sw = new Stopwatch();
int total = 0;
StringBuilder builder = new StringBuilder();
for (int trial = 0; trial < 2; ++trial)
{
sw.Restart();
total += loop1();
builder.AppendLine("loop1() took " + sw.Elapsed);
sw.Restart();
total += loop2();
builder.AppendLine("loop2() took " + sw.Elapsed);
sw.Restart();
total += loop3();
builder.AppendLine("loop3() took " + sw.Elapsed);
//builder.AppendLine(); // Uncommenting this line makes a big difference!
}
builder.AppendLine(total.ToString());
return builder.ToString();
}
static int loop1()
{
bool done = false;
int total = 0;
for (int i = 0; i < 100000 && !done; ++i)
{
for (int j = 0; j < 100000 && !done; ++j)
{
for (int k = 0; k < 2; ++k)
{
if (i == 9900)
{
done = true;
break;
}
++total;
}
}
}
return total;
}
static int loop2()
{
int total = 0;
for (int i = 0; i < 100000; ++i)
{
for (int j = 0; j < 100000; ++j)
{
for (int k = 0; k < 2; ++k)
{
if (i == 9900)
{
goto exit;
}
++total;
}
}
}
exit: return total;
}
static int loop3()
{
int total = 0;
for (int i = 0; i < 100000; ++i)
{
for (int j = 0; j < 100000; ++j)
{
for (int k = 0; k < 2; ++k)
{
if (i == 9900)
{
k = 2;
j = 100000;
i = 100000;
}
else
{
++total;
}
}
}
}
return total;
}
}
}
Now my results are as follows:
builder.AppendLine() commented out:
loop1() took 00:00:06.6509471
loop2() took 00:00:06.7322771
loop3() took 00:00:01.5361389
loop1() took 00:00:06.5746730
loop2() took 00:00:06.7051531
loop3() took 00:00:01.5027345
-1004901888
builder.AppendLine() not commented out:
loop1() took 00:00:06.9444200
loop2() took 00:00:02.8960563
loop3() took 00:00:01.4759535
loop1() took 00:00:06.9036553
loop2() took 00:00:03.1514154
loop3() took 00:00:01.4764172
-1004901888
Note the difference in the loop2() timing when I do that. Does not compute!
I can reproduce that exactly. In addition though, I can make the variance go away like this:
private static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
for (int trial = 0; trial < 4; ++trial)
{
sw.Restart();
Interlocked.MemoryBarrier();
loop1();
Interlocked.MemoryBarrier();
Console.WriteLine("loop1() took " + sw.Elapsed);
sw.Restart();
Interlocked.MemoryBarrier();
loop2();
Interlocked.MemoryBarrier();
Console.WriteLine("loop2() took " + sw.Elapsed);
sw.Restart();
Interlocked.MemoryBarrier();
loop3();
Interlocked.MemoryBarrier();
Console.WriteLine("loop3() took " + sw.Elapsed);
// Console.WriteLine(); // <-- Uncomment this and the timings don't change now.
}
}
When I run with the MemoryBarriers, I get the second pattern no matter which way I run the test:
loop1() took ~1 sec
loop2() took ~7 secs
loop3() took ~1 sec
MemoryBarrier definition:
Synchronizes memory access as follows: The processor executing the current thread cannot reorder instructions in such a way that memory accesses prior to the call to MemoryBarrier execute after memory accesses that follow the call to MemoryBarrier.
Since the IL for the loops is identical between the 2 versions, and MemoryBarrier makes the variance disappear, I think we can conclude the variance is definitely the result of an optimization on the first pattern... maybe by the JITer... maybe by the CPU... not sure there.
My environment is the same, except I am using VS2012 & .NET 4.5 RTM.

Array.Contains runs very slow, anyone shed some light?

I have done some benchmark regarding List.Contains, Array.Contains, IEnumerable.Contains, ICollection.Contains and IList.Contains.
The results are:
array pure 00:00:45.0052754 // 45 sec, slow
array as IList 00:00:02.7900305
array as IEnumerable 00:00:46.5871087 // 45 sec, slow
array as ICollection 00:00:02.7449889
list pure 00:00:01.9907563
list as IList 00:00:02.6626009
list as IEnumerable 00:00:02.9541950
list as ICollection 00:00:02.3341203
As I find out that it would be very slow if call Array.Contains directly (which is equivalent to call IEnumerable)
Also I feel it is strange that MSDN array page doesn't have contains method listed in the extension method section.
Sample code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace arrayList
{
class Program
{
static void Main(string[] args)
{
Stopwatch watch = new Stopwatch();
Int64 n = 100000000;
Int64[] myarray = new Int64[] { 1, 2, 3 };
List<Int64> mylist = new List<Int64>(myarray);
watch.Start();
for (Int64 j = 0; j < n; j++)
{
bool i = myarray.Contains(2);
}
watch.Stop();
Console.WriteLine("array pure {0}", watch.Elapsed);
watch.Restart();
for (Int64 j = 0; j < n; j++)
{
bool i = (myarray as IList<Int64>).Contains(2);
}
watch.Stop();
Console.WriteLine("array as IList {0}",watch.Elapsed);
watch.Restart();
for (Int64 j = 0; j < n; j++)
{
bool i = (myarray as IEnumerable<Int64>).Contains(2);
}
watch.Stop();
Console.WriteLine("array as IEnumerable {0}",watch.Elapsed);
watch.Restart();
for (Int64 j = 0; j < n; j++)
{
bool i = (myarray as ICollection<Int64>).Contains(2);
}
watch.Stop();
Console.WriteLine("array as ICollection {0}",watch.Elapsed);
watch.Restart();
for (Int64 j = 0; j < n; j++)
{
bool i = mylist.Contains(2);
}
watch.Stop();
Console.WriteLine("list pure {0}", watch.Elapsed);
watch.Restart();
for (Int64 j = 0; j < n; j++)
{
bool i = (mylist as IList<Int64>).Contains(2);
}
watch.Stop();
Console.WriteLine("list as IList {0}", watch.Elapsed);
watch.Restart();
for (Int64 j = 0; j < n; j++)
{
bool i = (mylist as IEnumerable<Int64>).Contains(2);
}
watch.Stop();
Console.WriteLine("list as IEnumerable {0}", watch.Elapsed);
watch.Restart();
for (Int64 j = 0; j < n; j++)
{
bool i = (mylist as ICollection<Int64>).Contains(2);
}
watch.Stop();
Console.WriteLine("list as ICollection {0}", watch.Elapsed);
Console.ReadKey();
}
}
}
The way you are timing these are not sufficient. You need significantly larger inputs to get times representative of the algorithms. Yes Contains() will be slower than a simple linear search (something you've omitted) but the different calls are not going to have the times as you've shown. You're likely to not see any variation between the calls to Contains() when cast to the different types as in all likelihood, we're calling the same implementation for all of them.
Try this code for size:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
const int iterations = 1000000;
const long target = 7192;
var arr = Enumerable.Range(0, 10000).Select(i => (long)i).ToArray();
var list = arr.ToList();
bool result;
var arr0 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = LinearSearchArr(arr, target);
}
arr0.Stop();
var arr1 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
// actually Enumerable.Contains()
result = arr.Contains(target);
}
arr1.Stop();
var arr2 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = ((IList<long>)arr).Contains(target);
}
arr2.Stop();
var arr3 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = ((IEnumerable<long>)arr).Contains(target);
}
arr3.Stop();
var arr4 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = ((ICollection<long>)arr).Contains(target);
}
arr4.Stop();
var list0 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = LinearSearchList(list, target);
}
list0.Stop();
var list1 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = list.Contains(target);
}
list1.Stop();
var list2 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = ((IList<long>)list).Contains(target);
}
list2.Stop();
var list3 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = ((IEnumerable<long>)list).Contains(target);
}
list3.Stop();
var list4 = Stopwatch.StartNew();
for (var i = 0; i < iterations; i++)
{
result = ((ICollection<long>)list).Contains(target);
}
list4.Stop();
Console.WriteLine("array linear {0} ({1})", arr0.Elapsed, arr0.ElapsedTicks);
Console.WriteLine("array pure {0} ({1})", arr1.Elapsed, arr1.ElapsedTicks);
Console.WriteLine("array as IList {0} ({1})", arr2.Elapsed, arr2.ElapsedTicks);
Console.WriteLine("array as IEnumerable {0} ({1})", arr3.Elapsed, arr3.ElapsedTicks);
Console.WriteLine("array as ICollection {0} ({1})", arr4.Elapsed, arr4.ElapsedTicks);
Console.WriteLine("list linear {0} ({1})", list0.Elapsed, list0.ElapsedTicks);
Console.WriteLine("list pure {0} ({1})", list1.Elapsed, list1.ElapsedTicks);
Console.WriteLine("list as IList {0} ({1})", list2.Elapsed, list2.ElapsedTicks);
Console.WriteLine("list as IEnumerable {0} ({1})", list3.Elapsed, list3.ElapsedTicks);
Console.WriteLine("list as ICollection {0} ({1})", list4.Elapsed, list4.ElapsedTicks);
}
static bool LinearSearchArr(long[] arr, long target)
{
for (var i = 0; i < arr.Length; i++)
{
if (arr[i] == target)
{
return true;
}
}
return false;
}
static bool LinearSearchList(List<long> list, long target)
{
for (var i = 0; i < list.Count; i++)
{
if (list[i] == target)
{
return true;
}
}
return false;
}
}
}
Specs:
Windows 7 Professional 64-bit
Intel Core 2 Quad Q9550 # 2.83GHz
4x1GiB Corsair Dominator DDR2 1066 (PC2-8500)
Default .NET 4.0 Console App release build targeting x64:
array linear 00:00:07.7268891 (21379939)
array pure 00:00:12.1703848 (33674883)
array as IList 00:00:12.1764948 (33691789)
array as IEnumerable 00:00:12.5377771 (34691440)
array as ICollection 00:00:12.1827855 (33709195)
list linear 00:00:17.9288343 (49608242)
list pure 00:00:25.8427338 (71505630)
list as IList 00:00:25.8678260 (71575059)
list as IEnumerable 00:00:25.8500101 (71525763)
list as ICollection 00:00:25.8423424 (71504547)
Guess: IList/List use ICollection.Contains wich directly goes through elements in the collection using index.
Array and IEnumerable versions use IEnumerable.Contains that requires creation of enumrator and run genreic iteration code (like MoveNext calls).
Make sure you use the results of the Contains method somehow in your code so that it doesn't optimise that away. I am guessing in one situation it can use a hashtable, and in the others it has to do linear search. Either that or it is just not running your loop as it doesn't do anything.
Either way, who is ever going to write code that casts and then runs contains a million times...

C# heapSort ,System.Timers; to check algorithm time

I have to check HeapSort algorithm time in C# , my problem is that I Know I must use System.Timers , because I don't know how to measures the algorithm time.
I have to check the algorithm time for table contains 1000 ,10 000 , 100 000 and 1000 000 integers.
Help me good people please.
This is the code:
using System;
namespace Sort
{
class Program
{
public static void Adjust(int[] list, int i, int m)
{
int Temp = list[i];
int j = i * 2 + 1;
while (j <= m)
{
if (j < m)
if (list[j] < list[j + 1])
j = j + 1;
if (Temp < list[j])
{
list[i] = list[j];
i = j;
j = 2 * i + 1;
}
else
{
j = m + 1;
}
}
list[i] = Temp;
}
public static void HeapSort(int[] list)
{
int i;
//Boulding a heap
for (i = (list.Length - 1) / 2; i >= 0; i--)
Adjust(list, i, list.Length - 1);
for (i = list.Length - 1; i >= 1; i--)
{
int Temp = list[0];
list[0] = list[i];
list[i] = Temp;
Adjust(list, 0, i - 1);
}
}
static void Main(string[] args)
{
Console.Title = "HeapSort";
int i;
int[] a = { 12, 3, -12, 27, 34, 23, 1, 81, 45,
17, 9, 23, 11, 4, 121 };
Console.WriteLine("Data before sort ");
for (i = 0; i < a.Length; i++)
Console.Write(" {0} ", a[i]);
Console.WriteLine();
HeapSort(a);
Console.WriteLine("Data after sort");
for (i = 0; i < a.Length; i++)
Console.Write(" {0} ", a[i]);
Console.ReadLine();
}
}
}
I've write this with You help , does is good ?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Sort
{
class Program
{
public static void Adjust(int[] list, int i, int m)
{
int Temp = list[i];
int j = i * 2 + 1;
while (j <= m)
{
if (j < m)
if (list[j] < list[j + 1])
j = j + 1;
if (Temp < list[j])
{
list[i] = list[j];
i = j;
j = 2 * i + 1;
}
else
{
j = m + 1;
}
}
list[i] = Temp;
}
public static void HeapSort (int[] list)
{
int i;
//Boulding a heap
for (i = (list.Length - 1) / 2;i >=0;i--)
Adjust (list, i, list.Length - 1);
for ( i = list.Length - 1; i >= 1; i--)
{
int Temp = list [0];
list [0] = list [i];
list [i] = Temp;
Adjust (list, 0, i - 1);
}
}
static void Main(string[] args)
{
Console.Title = "HeapSort";
int i;
Random myRandom = new Random();//Creating instance of class Random
Stopwatch myTime = new Stopwatch(); //variable for time measurement
int[] a = new int[1000]; //table contents 1000 variables
for (i = 0; i < a.Length; i++)
a[i] = myRandom.Next(100);
Console.WriteLine("Data before sort ");
for (i = 0; i < a.Length; i++)
Console.Write(" {0} ", a[i]);
Console.WriteLine();
myTime.Start();
HeapSort(a);
myTime.Stop();
string TimeEl = myTime.Elapsed.ToString();
Console.WriteLine("Data after sort");
for (i = 0; i < a.Length; i++)
Console.Write(" {0} ", a[i]);
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("time elapsed: {0} ", TimeEl);
Console.ReadLine();
}
}
}
If you're looking for time measurements, use the Stopwatch class.
This allows you to easily measure some time using the Start() and Stop() method. The Elapsed property will then tell you how long the operation took.
You could use the Stopwatch class to measure time:
var watch = Stopwatch.StartNew();
SomeFunctionThatCallsYourAlgorithm();
watch.Stop();
Console.WriteLine("algorithm execution time: {0}ms", watch.ElapsedMilliseconds);
There's some code from Vance Morrison's weblog that uses the Stopwatch class (as described above), but does multiple runs and performs some statistical analysis to give you the mean, median runtime, along with the standard derivation.
Check it out here:
Link

Categories

Resources