基准何时开始?

时间:2015-01-19 09:24:57

标签: c# .net

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()));
    }
}

有没有更好的方法来获得Stopwatch开始日期/时间?我正在寻找像sw.GetStartDateTime()这样的东西。

2 个答案:

答案 0 :(得分:4)

只需从sw.Elapsed中减去DateTime.Now即可获得起点。

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));

答案 1 :(得分:-1)

更好的方法是使用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"));