我还需要显示分钟,实际上我使用此代码来显示秒,但也需要分钟
TimeSpan ts = stopwatch.Elapsed;
Console.WriteLine("File Generated: " + _writer.getBinaryFileName(filePath, Convert.ToInt32(logSelected)) + " in " + "{0}.{1:D2}" + "seconds",
ts.Seconds,
ts.Milliseconds/10 + "\n"
);
我该怎么办?
您应该使用:
ts.ToString("mm\\:ss\\.ff")
这将为您提供时间间隔内的分钟、秒和百分之一秒。
另请查看 http://msdn.microsoft.com/en-us/library/ee372287.aspx
编辑: 如果您希望分钟成为最大单位,您可以执行以下操作:
string.Format("{0}:{1}", Math.Floor(ts.TotalMinutes), ts.ToString("ss\\.ff"))
.NET 4.0 中的 TimeSpan.ToString() 方法有一个重载,可让您指定格式。
显示分钟和秒:
TimeSpan elapsed = GetElapsedTime(); // however you get the amount of time elapsed
string tsOut = elapsed.ToString(@"m\:ss");
要包含毫秒,您可以这样写:
string tsOut = elapsed.ToString(@"m\:ss\.ff");
但请注意,如果总时间跨度超过 60 分钟,这将不会达到您的预期。显示的“分钟”值将是
elapsed.Minutes
,与 ((int)elapsed.TotalMinutes) % 60)
基本相同。所以如果总时间是70分钟,上面会显示10:00
。
如果你想可靠地显示总分钟和秒数,你必须自己计算。
int minutes = (int)elapsed.TotalMinutes;
double fsec = 60 * (elapsed.TotalMinutes - minutes);
int sec = (int)fsec;
int ms = 1000 * (fsec - sec);
string tsOut = String.Format("{0}:{1:D2}.{2}", minutes, sec, ms);
我是这样编码的:
using System.Diagnostics;
...
Stopwatch watch = new Stopwatch();
watch.Start();
// here the complex program.
...
watch.Stop();
TimeSpan timeSpan = watch.Elapsed;
Console.WriteLine("Time: {0}h {1}m {2}s {3}ms", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds);
//试试吧
Stopwatch sw = new Stopwatch();
sw.Start();
Thread.Sleep(10382);
sw.Stop();
Console.Write(sw.Elapsed.Duration());
TimeTakenOutput.Text = "0" + myStopWatch.Elapsed.Minutes.ToString()
+ ":" + myStopWatch.Elapsed.Seconds.ToString() + "mins";
简短回答:
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// your code
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine($"Process took {elapsedTime}");
为了可重用性和更好的结构,创建一个类,Watcher:
public static class Watcher {
// method to start a stopwatch
public static Stopwatch StartWatch()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
return stopwatch;
}
// method to stop a stopwatch
public static void StopWatch(Stopwatch stopwatch)
{
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine($"Process took {elapsedTime}");
}
}
现在在代码中的任何位置使用它:
var sw = Watcher.StartWatch();
// your code here
Watcher.StopWatch(sw);
ts.Minutes