用C#写一个特性,在函数上面可以自动计算函数耗时情况
TimingAttribute类是自定义的特性类,用来标记需要计时的方法。TimingInterceptor类是一个拦截器,它通过反射来拦截被TimingAttribute标记的方法,并在方法执行前后进行计时。MyClass中的MyMethod方法被标记为需要计时,当调用这个方法时,它会被TimingInterceptor拦截,计算执行时间并输出。
using System;
using System.Diagnostics;
using System.Reflection;
[AttributeUsage(AttributeTargets.Method)]
public class TimingAttribute : Attribute
{
public void OnEntry()
{
Console.WriteLine("Method execution started.");
}
public void OnExit(double milliseconds)
{
Console.WriteLine($"Method execution finished. Elapsed time: {milliseconds} milliseconds");
}
}
public class TimingInterceptor
{
public void Intercept(MethodInfo targetMethod)
{
var timingAttribute = (TimingAttribute)targetMethod.GetCustomAttribute(typeof(TimingAttribute));
if (timingAttribute != null)
{
timingAttribute.OnEntry();
var stopwatch = Stopwatch.StartNew();
targetMethod.Invoke(null, null);
stopwatch.Stop();
timingAttribute.OnExit(stopwatch.Elapsed.TotalMilliseconds);
}
else
{
targetMethod.Invoke(null, null);
}
}
}
public class MyClass
{
[Timing]
public static void MyMethod()
{
// 模拟一个耗时的操作
System.Threading.Thread.Sleep(2000);
Console.WriteLine("MyMethod executed.");
}
}
class Program
{
static void Main(string[] args)
{
TimingInterceptor interceptor = new TimingInterceptor();
MethodInfo method = typeof(MyClass).GetMethod("MyMethod");
interceptor.Intercept(method);
}
}