前言
在 .NET 开发中,我们经常需要对关键方法进行耗时监控,以识别性能瓶颈。虽然 Stopwatch 是实现这一目标的常见选择,但其使用方式高度侵入:必须手动添加开始、结束和日志记录代码。当这类计时逻辑遍布项目各处时,不仅造成大量重复代码,还让业务逻辑变得混乱不堪,极大影响了代码的整洁性与可维护性。
项目介绍
MethodTimer是一个.NET开源、免费(MIT License)、轻量级的运行耗时统计库,用于在编译时自动向指定方法注入计时代码,无需手动编写繁琐的计时逻辑。
创建控制台应用
创建名为:MethodTimerExercise
的控制台应用。
安装NuGet
命令安装
PM> Install-Package Fody
PM> Install-Package MethodTimer.Fody
NuGet包管理器安装
搜索Fody
安装:
搜索MethodTimer.Fody
安装:
快速使用
通过在方法上添加 Time
属性,MethodTimer 会在编译时自动向 TimeMethod
注入计时代码。
[Time]
public static void TimeMethod()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine($"输出结果{i}");
}
}
使用ILSpy查看编译后的代码
public static void TimeMethod()
{
Stopwatch stopwatch = Stopwatch.StartNew();
try
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine($"输出结果{i}");
}
}
finally
{
stopwatch.Stop();
string message = null;
MethodTimeLogger.Log(MethodBase.GetMethodFromHandle((RuntimeMethodHandle)/*OpCode not supported: LdMemberToken*/, typeof(Program).TypeHandle), stopwatch.Elapsed, message);
}
}
耗时拦截器记录两种方法
运行耗时为long(毫秒):
/// <summary>
/// 运行耗时为long(毫秒)
/// </summary>
public static class MethodTimeLogger1
{
public static void Log(MethodBase methodBase, long milliseconds, string message)
{
Console.WriteLine($"方法:{methodBase.Name} 耗时:{milliseconds} 毫秒,信息:{message}");
}
}
运行耗时为TimeSpan:
/// <summary>
/// 运行耗时为TimeSpan
/// </summary>
public static class MethodTimeLogger
{
public static void Log(MethodBase methodBase, TimeSpan elapsed, string message)
{
Console.WriteLine($"方法:{methodBase.Name} 耗时:{elapsed.TotalMilliseconds} 毫秒,信息:{message}");
}
}
耗时统计时长输出
项目源码地址
更多项目实用功能和特性欢迎前往项目开源地址查看👀,别忘了给项目一个Star支持💖。
- 开源地址:https://github.com/Fody/MethodTimer
- MethodTimerExercise:https://github.com/YSGStudyHards/DotNetExercises/tree/master/MethodTimerExercise
优秀项目和框架精选
该项目已收录到C#/.NET/.NET Core优秀项目和框架精选中,关注优秀项目和框架精选能让你及时了解C#、.NET和.NET Core领域的最新动态和最佳实践,提高开发工作效率和质量。坑已挖,欢迎大家踊跃提交PR推荐或自荐(让优秀的项目和框架不被埋没🤞)。