Create a class named StopWatch. The class contains: Private data fields startTim
ID: 3673796 • Letter: C
Question
Create a class named StopWatch. The class contains:
Private data fields startTime and endTime with getter methods
A no-arg constructor that initializes startTime with the current time.
A method named start() that resets the startTime to the current time
A method named stop() that resets the stopTime to the current time
A method named getElapsedtime() that returns the elaspsed time for the stopwatch in milliseconds
Write a test program that uses the StopWatch class to measure the execution time of sorting 100,000 numbers with insertion sort. Print the results in a formatted table.
Explanation / Answer
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();
}
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());
}
/ 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);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.