C#添加测量运行时间

2016年01月25日 14:24 0 点赞 0 评论 更新于 2025-11-21 19:44

在模块化开发中,每个模块通常都具备初始化功能,这些初始化功能可能涵盖加载配置表、初始化事件以及初始化设置等操作。那么,如何测量每个模块的初始化(Init)时间呢?.NET 框架已经为我们提供了相应的测量运行时间的方法。

System.Diagnostics 命名空间

System.Diagnostics 命名空间包含了一系列类型,这些类型能让我们与系统进程、事件日志和性能计数器进行交互。其部分子命名空间中的类型还具备以下功能:与代码分析工具交互、支持协定、扩展对应用程序监控和检测的设计时支持、使用 Windows 事件跟踪 (ETW) 跟踪子系统记录事件数据、在事件日志中进行读写操作、收集性能数据以及读写调试符号信息。

System.Diagnostics.Stopwatch 类

System.Diagnostics.Stopwatch 类提供了一组方法和属性,可用于准确地测量运行时间。你可以通过以下 MSDN 文档链接获取更详细的信息:https://msdn.microsoft.com/zh-cn/library/system.diagnostics.stopwatch(v=vs.110).aspx

辅助类实现

下面是一个自定义的 PerformanceHelper 类,用于简化测量运行时间的操作:

public class PerformanceHelper
{
// 添加性能观察
public static void AddWatch(Action del)
{
AddWatch("执行耗费时间: {0}s", del);
}

public static void AddWatch(string outputStr, Action del)
{
// 判断是否检测运行时间
if (Debug.isDebugBuild)
{
System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
// 开始监视代码运行时间
stopwatch.Start();

if (del != null)
{
del();
}

// 停止监视
stopwatch.Stop();
// 获取当前实例测量得出的总时间
TimeSpan timespan = stopwatch.Elapsed;
// 总毫秒数
double millseconds = timespan.TotalMilliseconds;
decimal seconds = (decimal)millseconds / 1000m;
// 7 位精度
Debug.Log(string.Format(outputStr, seconds.ToString("F7")));
}
else
{
if (del != null)
{
del();
}
}
}
}

使用方法示例

以下是如何使用 PerformanceHelper 类来测量 GameSetting 模块初始化时间的示例:

public class GameSetting
{
// 初始化
public void Init()
{
PerformanceHelper.AddWatch("Init Gamesetting :{0}s", LoadConfig);
}

public void LoadConfig()
{
// TODO 加载配置表
}
}

通过上述方式,我们可以方便地测量每个模块初始化操作的运行时间,有助于我们对程序性能进行监控和优化。

作者信息

洞悉

洞悉

共发布了 3994 篇文章