写这个类的目的是想测试部分代码的执行时间,比起直接在代码里加DateTime span , 它使用起来更方便一些。
你也可以随时控制什么时候输出性能信息。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
namespace Perf
{
public class PerformanceChecker
{
private StringBuilder m_Log;
public StringBuilder Log
{
get { return m_Log; }
set { m_Log = value; }
}
public DateTime m_StartTime;
public PerformanceChecker()
{
Initialize();
}
public void Initialize()
{
m_Log = new StringBuilder();
}
public void Start()
{
m_StartTime = DateTime.Now;
}
public void Stop(string title)
{
m_Log.AppendLine(GetTimeSpan(title));
}
public void Output()
{
string logFile = System.AppDomain.CurrentDomain.BaseDirectory + Guid.NewGuid().ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(logFile))
{
sw.Write(m_Log.ToString());
sw.Flush();
}
Process.Start(logFile);
m_Log = new StringBuilder();
}
private string GetTimeSpan(string title)
{
DateTime now = DateTime.Now;
string resultString = now.ToString("yyyy/MM/dd HH:mm:ss") + " --> Title:" + title + " TimeSpan:"+ (now - m_StartTime).ToString();
return resultString;
}
}
}
使用方法:
PerformanceChecker perfChecker = new PerformanceChecker();
perfChecker.Start();
//The method1 execution....
perfChecker.Stop("Method1 execution.");
perfChecker.Start();
//The method2 execution....
perfChecker.Stop("Method2 execution.");
// Popup a notepad instance shows the log.
perfChecker.Output();
本文介绍了一个用于测试代码执行时间的性能检查类,包括初始化、开始计时、停止计时并输出性能信息到日志文件的功能。通过实例演示了如何在方法执行前后调用该类的方法来获取性能数据,并提供了日志文件查看性能结果的步骤。

3345

被折叠的 条评论
为什么被折叠?



