C# – Stopwatch elapsed output

c

I had some code that crunched a lot of data, so I started it on Thursday and left it running over the weekend. On Monday, I have come back and seen that it finished. I used a stopwatch function to track the length of time the code ran for. However, I ended up with

Elapsed: 2.18:57:55.xxx

I understand that it's output is normally H:M:SS, but don't understand the first digit, especially since it's been running for days. Did it just convert from hours to days? Did I leave it running so long that it broke?

EDIT: Sorry, I didn't mean that it finished on Monday. I just meant that BY Monday (when I returned to the computer), it was done.

Best Answer

Yes - that's the format of TimeSpan.ToString:

The returned string is formatted with the "c" format specifier and has the following format:

[-][d.]hh:mm:ss[.fffffff]

Elements in square brackets ([ and ]) may not be included in the returned string. Colons and periods (: and.) are literal characters. The non-literal elements are listed in the following table. Note that the string returned by the ToString() method is not culture-sensitive.

Since there's not a format specifier that shows total hours, you'll need to calculate it. If you want the hours to be shown as a single number then use:

TimeSpan ts = new TimeSpan(2,18,57,55);
    
var output = string.Format("{0}:{1}",
                           ts.Days*24 + ts.Hours,
                           ts.ToString("mm\\:ss\\.ffff"));

//output =  `66:57:55.0000`
Related Topic