所谓计时,就是统计代码在运行到某处时记一个时刻值,然后再运行到某处时再记一个时刻值,来衡量中间这段代码执行的时间的方法。

使用这样的方法,前提是要忽略CPU的多线程,操作系统的多线程,多任务这些因素,所以只能尽量得到一个相对值来比较两段代码的效率,而不能精确计算。

 

方法一: 用 DateTime.Now.Ticks

 

1 long start = 0;
2 long end = 0;
3
4 start = DateTime.Now.Ticks;
5
6 Console.WriteLine("start ticks is:{0}",start);
7
8 decimal result = 0;
9 try
10 {
11 for (int i = 0; i < Int32.MaxValue; i++)
12 {
13 checked
14 {
15 result += i;
16 }
17 }
18 }
19 catch
20 {
21 Console.WriteLine("Exception!");
22 }
23
24 end = DateTime.Now.Ticks;
25
26 Console.WriteLine("end ticks is:{0}",end);
27
28 Console.WriteLine("elapsed ticks:{0}",end-start);
29
30 Console.WriteLine("it is {0} seconds!", (end - start) / 10000000);

 

根据MSDN的解释,

A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond.

1个 tick 代表100纳秒,1毫秒等于10000个ticks,也就是说,1秒等于 1E7 个ticks。

任何一个 DateTime 型变量中都有一个 ticks 属性,它代表从 12:00:00 midnight, January 1, 0001 到当前时间值的间隔的 ticks 值。

用上面的方法,最精确,应该也就是精确到1tick,即100纳秒。


 

方法二: 借助 StopWatch 类

 

StopWatch类是来自于 System.Diagnostics 命名空间的一个类。大概的使用方法如下:

 

1 Stopwatch MyStopWatch = new Stopwatch();
2 MyStopWatch.Start();
3
4 result = 0;
5 try
6 {
7 for (int i = 0; i < Int32.MaxValue; i++)
8 {
9 checked
10 {
11 result += i;
12 }
13 }
14 }
15 catch
16 {
17 Console.WriteLine("Exception!");
18 }
19
20 MyStopWatch.Stop();
21
22 decimal t = MyStopWatch.ElapsedTicks;
23
24 Console.WriteLine();
25
26 Console.WriteLine("Statistics by StopWatch is:{0} ticks!", t);
27 Console.WriteLine("it is {0} seconds!", t / 10000000);

 

可以选的统计Start 与 Stop 之间时间段的属性有:

 

Elapsed();        返回一个 TimeSpan 对象。

ElapsedTicks(); 返回一个 Ticks 值。

ElapsedMilliseconds;返回一个 毫秒 值。

 

.NET/C#中的计时方法

 

问题是,同样的计算了个

 

 7                 for (int i = 0; i < Int32.MaxValue; i++)
8 {
9 checked
10 {
11 result += i;
12 }
13 }

块,用两种方法统计出来的结果,差距怎么那么巨大呀??????300倍。。。。。不明白

 

 

相关文章:

  • 2021-12-18
  • 2022-12-23
  • 2021-12-27
  • 2022-12-23
  • 2021-09-04
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-29
  • 2021-12-30
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案