我在想這樣做的:如何製作秒錶控制檯?
int intCount = 0;
int intConstant = ...;
while(true)
{
Console.WriteLine(intCount/intConstant + " seconds");
}
但我不知道如何找出不變,使秒錶計數秒。
我在想這樣做的:如何製作秒錶控制檯?
int intCount = 0;
int intConstant = ...;
while(true)
{
Console.WriteLine(intCount/intConstant + " seconds");
}
但我不知道如何找出不變,使秒錶計數秒。
不要使用循環,這將是處理器特定的。更好地利用StopWatch
類:
var watch = StopWatch.StartNew();
while(true)
{
Console.WriteLine(watch.ElapsedMilliseconds/1000f + " seconds");
}
爲什麼你除以1000f而不是1000? – RedAces
@RedAces:如果你除以1000,你會得到一個四捨五入的整數。除以1000f會給你一個更精確的浮點數。 – pascalhein
考慮你想要什麼猜測,這樣做:
Stopwatch sw = new Stopwatch();
sw.Start();
while(true)
{
Console.WriteLine(sw.ElapsedMilliseconds/1000 + " seconds");
}
您可以在System.Diagnostics namespace
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds/10);
Console.WriteLine("RunTime " + elapsedTime);
使用秒錶類有一類爲HTTP ://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx –
BCL中有多個Timer類。請參閱:http://msdn.microsoft.com/en-us/magazine/cc164015.aspx - 舊但仍相關。 – Oded
您將無法使用常量,因爲循環不會始終以相同的速度運行。 – computer10171