I am new to C# world. I am attempting to calculate time taken by a algorithum for the purpose of comparison. Following code measures the elapsed time from when a subroutine is called until the subroutine returns to the main program.This example is taken from "Data structures through C#" by Michael McMillan. After running this program the output is Time=0, which is incorrect. The program appears to be logically correct. Can anybody help me. Following is the code
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Chap1
{
class chap1
{
static void Main()
{
int[] nums = new int[100000];
BuildArray(nums);
Timing tObj = new Timing();
tObj.startTime();
DisplayNums(nums);
tObj.stopTime();
Console.WriteLine("Time: " + tObj.result().TotalSeconds);
Console.WriteLine("Start Time: " + tObj.startTime().TotalSeconds);
Console.WriteLine("Duration : " + tObj.result().TotalSeconds);
Console.ReadKey();
}
static void BuildArray(int[] arr)
{
for (int i = 0; i <= 99999; i++)
arr[i] = i;
}
static void DisplayNums(int[] arr)
{
for (int i = 0; i <= arr.GetUpperBound(0); i++)
Console.WriteLine(arr[i]);
}
}
class Timing
{
TimeSpan StartTiming;
TimeSpan duration;
public Timing()
{
StartTiming = new TimeSpan(0);
duration = new TimeSpan(0);
}
public TimeSpan startTime()
{
GC.Collect();
GC.WaitForPendingFinalizers();
StartTiming = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
return StartTiming;
}
public void stopTime()
{
duration = Process.GetCurrentProcess().Threads[0].UserProcessorTime.Subtract(StartTiming);
}
public TimeSpan result()
{
return duration;
}
}
}