[转载]如何统计代码行执行的时间? – b0b0 – 博客园.
1. 问题
请计算下列代码执行所耗费的时间,给出通用的解决方法?
List myList=new List(); for(Int32 i=0;i<ICount;i++) { myList.Add(i); }
2. 解决方法
using (OperationTimer op=new OperationTimer ("Generic ")) { ListmyList=new List(); for(Int32 i=0;i<ICount;i++) { myList.Add(i); } } }
OperationTimer 类会在调用构造函数时取得时间t1,在调用Dispose()取得时间t2,中间过程耗费的时间=t2-t1. Using 语法会在using 块的末尾调用using中声明对象的Dispose方法。
3. 代码
using System; using System.Diagnostics; using System.Collections; using System.Collections.Generic; namespace genericApp { ///计时辅助类 public class OperationTimer:IDisposable{ private Int64 m_startTime; private string m_text; private Int32 m_CollectionCount; public OperationTimer(string text) { m_startTime=Stopwatch.GetTimestamp(); m_text=text; } public void Dispose() { string text=string.Format("Time={0,6:###.00}",(Stopwatch.GetTimestamp()-m_startTime)/Stopwatch.Frequency); Console.WriteLine(string.Format("{0}:{1}",m_text,text)); } } class MainClass { public static void Main(string[] args) { ValueTypePerfermanceTest(); Console.Read(); } static void ValueTypePerfermanceTest() { const Int32 ICount=20000000; using (OperationTimer op=new OperationTimer ("Generic ")) { ListmyList=new List(); for(Int32 i=0;i<ICount;i++) { myList.Add(i); } } using (OperationTimer op2=new OperationTimer ("ArrayList ")) { ArrayList myList=new ArrayList(); for(Int32 i=0;i<ICount;i++) { myList.Add(i); } } } } }
4. Mono 2.4 中的运行结果