博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Stopwatch的使用
阅读量:7070 次
发布时间:2019-06-28

本文共 1812 字,大约阅读时间需要 6 分钟。

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6  7 namespace Stopwatch的使用 8 { 9     class Program10     {11       12         /// 13         /// 使用Stopwatch比较for循环和foreach循环的效率14         /// 15         /// 16         static void Main(string[] args)17         {18 19             int[] intArr = new int[1000000];20             for (int i = 1; i <= 1000000; i++)21             {22                 intArr[i - 1] = i;23             }24 25             //使用Stopwatch统计程序运行的时间26             /*27              Stopwatch提供了几个方法用以控制Stopwatch对象。28              * Start方法开始一个计时操作,Stop方法停止计时。29              * 此时如果第二次使用 Start方法,将继续计时,最终的计时结果为两次计时的累加。30              * 为避免这种情况,在第二次计时前用Reset方法将对象归零。这三个方法都不需要参数31              */32             System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); 33             sw.Start(); //开始计时34 35             int sum = 0;36 37             for (int i = 1; i <= intArr.Length; i++)38             {39                 sum += i;40             }41             Console.WriteLine("sum={0}",sum);42            43             sw.Stop(); //停止计时44             long result = sw.ElapsedMilliseconds;//获得程序运行的时间45             Console.WriteLine("使用for循环计算从1加到1000000的和所需要的时间是:{0}", result);46 47             Console.WriteLine("****************************************************************");48             sw.Reset();49             sw.Start();50 51             sum = 0;52             foreach (var item in intArr)53             {54                 sum += item;55             }56             Console.WriteLine("sum={0}", sum);57             Console.WriteLine("使用foreach循环计算从1加到1000000的和所需要的时间是:{0}", sw.ElapsedMilliseconds);58             sw.Stop();59 60             Console.ReadKey();61         }62     }63 }

 

转载地址:http://pozml.baihongyu.com/

你可能感兴趣的文章
[Soot学习笔记][5]Soot依赖的两个框架
查看>>
[导入]构筑在GPRS之上的WAP应用
查看>>
POJ 2409 Let it Bead
查看>>
javase之四种内部类
查看>>
基于FPGA的AD0832
查看>>
Django 碎片集合
查看>>
Merge与Rebase冲突的解决
查看>>
python中自定义排序函数
查看>>
微信快速开发框架(五)-- 利用快速开发框架,快速搭建微信浏览博客园首页文章...
查看>>
hdu-1532 Drainage Ditches---最大流模板题
查看>>
mysql分表和表分区详解
查看>>
前端规范1-HTML规范
查看>>
NYOJ 6(贪心)
查看>>
深入学习hbase:表,列族,列标识,版本和cell
查看>>
android中同源策略绕过类漏洞学习笔记
查看>>
MYSQL数据库
查看>>
linux环境搭建seafile客户端自动上传文件
查看>>
10.27 函数
查看>>
MySQL查询缓存
查看>>
【问题总结】问题行
查看>>