C#利用特性来计算函数运行的时间

C S h a r p 利 用 特 性 来 计 算 函 数 运 行 的 时 间 CSharp利用特性来计算函数运行的时间 CSharp

项目结构

在这里插入图片描述

用起来有点限制,目前只能用在的类里面的方法

第一步:编写类的装饰器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Test4Decropter
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class CalculateTimeAttribute : ContextAttribute, IContributeObjectSink
    {
        public CalculateTimeAttribute() : base("Decorator")
        {
        }

        public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
        {
            return new Decorator(nextSink);
        }
    }

}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Test4Decropter
{


public class Decorator : IMessageSink
{
    public Decorator(IMessageSink nextSink)
    {
        _NextSink = nextSink;
    }
    #region IMessageSink
    private IMessageSink _NextSink;
    public IMessageSink NextSink
    {
        get
        {
            return _NextSink;
        }
    }
    public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
    {
        throw new NotImplementedException();
    }
    public IMessage SyncProcessMessage(IMessage msg)
    {
        IMessage result = null;
        var call = msg as IMethodCallMessage;
        if (call == null || Attribute.GetCustomAttribute(call.MethodBase, typeof(CalculateTimeMethodAttribute)) == null)
        {
            result = NextSink.SyncProcessMessage(msg);
        }
        else
        {
            var attr = Attribute.GetCustomAttribute(call.MethodBase, typeof(CalculateTimeMethodAttribute)) as CalculateTimeMethodAttribute;
            Console.WriteLine(attr.PrefixPrint);
                DateTime AlgorithmProStartTime = DateTime.Now;
                Console.WriteLine("开始时间:"+ AlgorithmProStartTime.ToString());
                result = NextSink.SyncProcessMessage(msg);
                DateTime AlgorithmProEndTime = DateTime.Now;
                Console.WriteLine("结束时间:" + AlgorithmProEndTime.ToString());
                Console.WriteLine(attr.SuffixPrint);
                Console.WriteLine("消耗时间:" + (AlgorithmProEndTime - AlgorithmProStartTime).ToString("ssfff"));
            }
        return result;
    }
    #endregion
}
}

第二步:编写方法的装饰器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test4Decropter
{


    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class CalculateTimeMethodAttribute : Attribute
    {
        public CalculateTimeMethodAttribute()
        {
            PrefixPrint = "function start";
            SuffixPrint = "function end";
        }
        public CalculateTimeMethodAttribute(String strPrefixPrint, String strSuffixPrint)
        {
            PrefixPrint = strPrefixPrint;
            SuffixPrint = strSuffixPrint;
        }
        public String PrefixPrint { get; set; }
        public String SuffixPrint { get; set; }
    }

}

第三步:编写正常需要使用的类,需要继承ContextBoundObject和使用第一步的类特性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Test4Decropter
{
    [CalculateTime]
    public class SomeClass : ContextBoundObject
    {
        [CalculateTimeMethod]
        public void SomeAction()
        {
            Console.WriteLine("do some Action");
            Thread.Sleep(3000);
        }

        [CalculateTimeMethod(PrefixPrint = "begin the calculate", SuffixPrint = "end the calculate")]
        public Int32 SomeCalculate(Int32 a, Int32 b)
        {
            var sum = a + b;
            Console.WriteLine("do some Calculate:{0} plus {1} equals {2}", a, b, sum);
            Thread.Sleep(3000);
            return sum;
        }

        [CalculateTimeMethod]
        public void test()
        {
            Console.WriteLine("hello major");
            Thread.Sleep(3000);
        }
    }
}

第四步:主程序调用

在这里插入代码片```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Test4Decropter
{
    class Program
    {


        static void Main(string[] args)
        {
            var sc = new SomeClass();
            sc.test();
            sc.SomeAction();
            Console.WriteLine();
            sc.SomeCalculate(5, 8);
            Console.Read();
        }
    }
}

全部代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Test4Decropter
{
    class Program
    {


        static void Main(string[] args)
        {
            var sc = new SomeClass();
            sc.test();
            sc.SomeAction();
            Console.WriteLine();
            sc.SomeCalculate(5, 8);
            Console.Read();
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Test4Decropter
{
    [CalculateTime]
    public class SomeClass : ContextBoundObject
    {
        [CalculateTimeMethod]
        public void SomeAction()
        {
            Console.WriteLine("do some Action");
            Thread.Sleep(3000);
        }

        [CalculateTimeMethod(PrefixPrint = "begin the calculate", SuffixPrint = "end the calculate")]
        public Int32 SomeCalculate(Int32 a, Int32 b)
        {
            var sum = a + b;
            Console.WriteLine("do some Calculate:{0} plus {1} equals {2}", a, b, sum);
            Thread.Sleep(3000);
            return sum;
        }

        [CalculateTimeMethod]
        public void test()
        {
            Console.WriteLine("hello major");
            Thread.Sleep(3000);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Test4Decropter
{


public class Decorator : IMessageSink
{
    public Decorator(IMessageSink nextSink)
    {
        _NextSink = nextSink;
    }
    #region IMessageSink
    private IMessageSink _NextSink;
    public IMessageSink NextSink
    {
        get
        {
            return _NextSink;
        }
    }
    public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
    {
        throw new NotImplementedException();
    }
    public IMessage SyncProcessMessage(IMessage msg)
    {
        IMessage result = null;
        var call = msg as IMethodCallMessage;
        if (call == null || Attribute.GetCustomAttribute(call.MethodBase, typeof(CalculateTimeMethodAttribute)) == null)
        {
            result = NextSink.SyncProcessMessage(msg);
        }
        else
        {
            var attr = Attribute.GetCustomAttribute(call.MethodBase, typeof(CalculateTimeMethodAttribute)) as CalculateTimeMethodAttribute;
            Console.WriteLine(attr.PrefixPrint);
                DateTime AlgorithmProStartTime = DateTime.Now;
                Console.WriteLine("开始时间:"+ AlgorithmProStartTime.ToString());
                result = NextSink.SyncProcessMessage(msg);
                DateTime AlgorithmProEndTime = DateTime.Now;
                Console.WriteLine("结束时间:" + AlgorithmProEndTime.ToString());
                Console.WriteLine(attr.SuffixPrint);
                Console.WriteLine("消耗时间:" + (AlgorithmProEndTime - AlgorithmProStartTime).ToString("ssfff"));
            }
        return result;
    }
    #endregion
}
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace Test4Decropter
{
    [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
    public class CalculateTimeAttribute : ContextAttribute, IContributeObjectSink
    {
        public CalculateTimeAttribute() : base("Decorator")
        {
        }

        public IMessageSink GetObjectSink(MarshalByRefObject obj, IMessageSink nextSink)
        {
            return new Decorator(nextSink);
        }
    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test4Decropter
{


    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class CalculateTimeMethodAttribute : Attribute
    {
        public CalculateTimeMethodAttribute()
        {
            PrefixPrint = "function start";
            SuffixPrint = "function end";
        }
        public CalculateTimeMethodAttribute(String strPrefixPrint, String strSuffixPrint)
        {
            PrefixPrint = strPrefixPrint;
            SuffixPrint = strSuffixPrint;
        }
        public String PrefixPrint { get; set; }
        public String SuffixPrint { get; set; }
    }

}

参考文档:

https://blog.csdn.net/aimanbing4182/article/details/101327320

https://www.zhihu.com/question/36211661?sort=created

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
c#从入门到精通第四版的pptC#是微软公司发布的一种面向对象的、运行于.NET Framework之上的高级程序设计语言。并定于在微软职业开发者论坛(PDC)上登台亮相。C#是微软公司研究员Anders Hejlsberg的最新成果。C#看起来与Java有着惊人的相似;它包括了诸如单一继承、接口、与Java几乎同样的语法和编译成中间代码再运行的过程。但是C#与Java有着明显的不同,它借鉴了Delphi的一个特点,与COM(组件对象模型)是直接集成的,而且它是微软公司 .NET windows网络框架的主角。 C#是一种安全的、稳定的、简单的、优雅的,由C和C++衍生出来的面向对象的编程语言。它在继承C和C++强大功能的同时去掉了一些它们的复杂特性(例如没有宏以及不允许多重继承)。C#综合了VB简单的可视化操作和C++的高运行效率,以其强大的操作能力、优雅的语法风格、创新的语言特性和便捷的面向组件编程的支持成为.NET开发的首选语言。 [1] C#是面向对象的编程语言。它使得程序员可以快速地编写各种基于MICROSOFT .NET平台的应用程序,MICROSOFT .NET提供了一系列的工具和服务来最大程度地开发利用计算与通讯领域。 C#使得C++程序员可以高效的开发程序,且因可调用由 C/C++ 编写的本机原生函数,因此绝不损失C/C++原有的强大的功能。因为这种继承关系,C#与C/C++具有极大的相似性,熟悉类似语言的开发者可以很快的转向C#。 [2]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值