Time required for a process to complete
Posted
by yelkawar
on Stack Overflow
See other posts from Stack Overflow
or by yelkawar
Published on 2010-04-05T03:33:07Z
Indexed on
2010/04/05
3:43 UTC
Read the original article
Hit count: 312
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.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
namespace Chap1
{
class Program
{
static void Main(string[] args)
{
int num1 = 100;
int num2 = 200;
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);
Swap<int>(ref num1, ref num2);
Console.WriteLine("num1: " + num1);
Console.WriteLine("num2: " + num2);
string str1 = "Sam";
string str2 = "Tom";
Console.WriteLine("String 1: " + str1);
Console.WriteLine("String 2: " + str2);
Swap<string>(ref str1, ref str2);
Console.WriteLine("String 1: " + str1);
Console.WriteLine("String 2: " + str2);
Console.ReadKey();
}
static void Swap<T>(ref T val1, ref T val2)
{
T temp;
temp = val1;
val1 = val2;
val2 = temp;
}
}
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;
}
}
}
© Stack Overflow or respective owner