内容载入中...
添加Stopwatch对象:
Stopwatch类位于System.Diagnostics命名空间。下面是添加对象后的代码:
using System;
using System.Diagnostics;
namespace StopWatchClass
{
class Program
{
static void Main(string[] args)
{
Stopwatch timer = new Stopwatch();
long total = 0;
for (int i = 1; i <= 10000000; i++)
{
total += i;
}
}
}
}
控制Stopwatch对象:
Stopwatch提供了几个方法用以控制Stopwatch对象。Start方法开始一个计时操作,Stop方法停止计时。此时如果第二次使用Start方法,将继续计时,最终的计时结果为两次计时的累加。为避免这种情况,在第二次计时前用Reset方法将对象归零。这三个方法都不需要参数。代码是:
using System;
using System.Diagnostics;
namespace StopWatchClass
{
class Program
{
static void Main(string[] args)
{
Stopwatch timer = new Stopwatch();
long total = 0;
timer.Start();
for (int i = 1; i <= 10000000; i++)
{
total += i;
}
timer.Stop();
}
}
}
读取Stopwatch结果:
<!--[if !supportLists]--><!--[endif]--> 在结束计时后下一步就是读取计时结果了。Stopwatch类提供了一下属性:
<!--[if !supportLists]--><!--[endif]--><!--[if !supportLists]--><!--[endif]-->
Elapsed:返回一个TimeSpan对象,表示计时时间间隔;
ElapsedMilliseconds:返回计时经过的微秒数,精确度稍差,适合于稍长一点的计时;
ElapsedTicks:返回计时经过的计时器刻度(timer tick)数。计时器刻度是Stopwatch对象可能的最小量度单位。计时器刻度时间的长度由特定的计算机和操作系统确定。Stopwatch对象的Frequency静态字段的值表示一秒所包含的计时器刻度数。注意它与TimeSpan的Ticks属性所用的时间单位的区别。
应当根据计时任务的情况选择其中的一个属性。在我们的示例程序中,Elapsed属性提供了需要的精确度,用它来输出经过的微秒数。这也是TimeSpan的最高精确度了。
下面是最终的程序代码:
using System;
using System.Diagnostics;
namespace StopWatchClass
{
class Program
{
static void Main(string[] args)
{
Stopwatch timer = new Stopwatch();
long total = 0;
timer.Start();
for (int i = 1; i <= 10000000; i++)
{
total += i;
}
timer.Stop();
decimal micro = timer.Elapsed.Ticks / 10m;
Console.WriteLine("Execution time was {0:F1} microseconds.", micro);
}
}
}
另外,使用IsRunning属性可以查看一个Stopwatch实例是否正在计时,使用StartNew方法可以开始一个新的计时器。
。