0
class Program
{
    Stopwatch sw = new Stopwatch();
    DateTime date;

    public static void Main()
    {
        date = Datetime.Now;
        sw.Start();
        // do some work
        sw.Stop();
        Log(String.Format("App started on {0}, run time is {1}.", date, sw.ToRedableString()));
    }
}

Is there a better way to get the Stopwatch start date/time? I'm looking for something like sw.GetStartDateTime().

cin
  • 351
  • 3
  • 14

2 Answers2

4

Just subtract sw.Elapsed from DateTime.Now and you'll have your starting point.

var sw = new Stopwatch();
sw.Start();
// do work
sw.Stop();
DateTime startDate = DateTime.Now.Subtract(sw.Elapsed);
Log(String.Format("App started on {0}, run time is {1}.", startDate, sw.Elapsed));
Jan Köhler
  • 5,817
  • 5
  • 26
  • 35
  • 1
    There is probably no benefit over using this compared to the OP's version. – leppie Jan 19 '15 at 09:30
  • 1
    @leppie I think he's looking for a way to do that, which is provided in my answer. His `sw.GetStartDateTime()` is just a dummy, I think. – Jan Köhler Jan 19 '15 at 09:31
-1

A better way of doing this is to use DateTimes

DateTime start = DateTime.Now;
// doWork()
DateTime end = DateTime.Now;
Log(String.Format("App started at {0}, run time is {1}.", start, (end - start).toString("HH:mm:ss"));
Alex Anderson
  • 840
  • 5
  • 11
  • 3
    What makes this 'better'? – leppie Jan 19 '15 at 09:36
  • 3
    DateTime is potentially lower precision than Stopwatch. Stopwatch uses a high precision timer if it's available: http://stackoverflow.com/questions/28637/is-datetime-now-the-best-way-to-measure-a-functions-performance – Dave R. Jan 19 '15 at 09:38
  • @leppie becuase this way you do not need to calculate the start time, you have it to the millisecond. If you need better resolution, you need better resolution. OP never stated he needed to track to the Femptosecond. – Alex Anderson Jan 19 '15 at 09:43
  • 2
    @AlexAnderson: `DateTime.Now` does not have millisecond accuracy, it does have millisecond resolution. And sometimes microseconds matters for micro-benchmarks. – leppie Jan 19 '15 at 09:46