0
点赞
收藏
分享

微信扫一扫

如何使用DEEPL免费翻译PDF

先峰老师 2024-05-12 阅读 35

用C#写一个特性,在函数上面可以自动计算函数耗时情况

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);
    }
}

举报

相关推荐

0 条评论