30

I have a really simple bit of code I use to test the response from proxy servers, I want to be able to start a timer and stop it and get the elapsed time it took for those to happen. However, I don't believe the code I have below is what I'm looking for.

var proxyStopWatch = new Timer();
proxyStopWatch.Start();

string[] splitProxy = ProxyList[i].Split('|');
string testResults = HTMLProcessor.HTMLProcessing.HTMLResults("http://www.google.com", splitProxy[0], Convert.ToInt32(splitProxy[1]), true, out testResults);

ProxyListResults.Add(ProxyList+"|"+proxyStopWatch.Interval.ToString());
proxyStopWatch.Stop();
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104

3 Answers3

67

To just get elapsed time, the Stopwatch class will probably be easier to use.

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();

// do stuff

stopWatch.Stop();
long duration = stopWatch.ElapsedMilliseconds;
Jeroen K
  • 10,258
  • 5
  • 41
  • 40
Jason
  • 86,222
  • 15
  • 131
  • 146
14

Here is an example that uses the stopwatch from System.Diagnostics namespace:

var stopWatch = new Stopwatch();
stopWatch.Start();

Thread.Sleep(10000);
stopWatch.Stop();

// Get the elapsed time as a TimeSpan value.
var ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = $"{ts.Hours}:{ts.Minutes}:{ts.Seconds}.{ts.Milliseconds / 10}";
    
Console.WriteLine("RunTime " + elapsedTime);
Irshu
  • 8,248
  • 8
  • 53
  • 65
Shiraz Bhaiji
  • 64,065
  • 34
  • 143
  • 252
1

You are right. I don't think that's what you are looking for. You can simply do:

var start = DateTime.Now;
string[] splitProxy = ProxyList[i].Split('|');

string testResults 
     = HTMLProcessor.HTMLProcessing.HTMLResults("http://www.google.com", 
     splitProxy[0], Convert.ToInt32(splitProxy[1]), true, out testResults);
ProxyListResults.Add(ProxyList+"|"+proxyStopWatch.Interval.ToString());

Console.WriteLine("Time elapsed in milliseconds was: " + 
    (DateTime.Now - start).TotalMilliseconds);
AustinWBryan
  • 3,249
  • 3
  • 24
  • 42
Diego
  • 18,035
  • 5
  • 62
  • 66