C# 监测每个方法的执行次数和占用时间(测试2)

在Nuget引用 Castle.DynamicProxy 和 Newtonsoft.Json 这个

原文:http://www.cnblogs.com/RicCC/archive/2010/03/15/castle-dynamic-proxy.html

代码:

using Castle.Core.Interceptor;
using Castle.DynamicProxy;
using ConsoleApplication1.test;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace ConsoleApplication2.AOP
{
    class Class5
    {
        static void Main(string[] args)
        {
            ProxyGenerator generator = new ProxyGenerator();//代理
            CallingLogInterceptor interceptor = new CallingLogInterceptor();//定义 拦截器
            Class5_test1 entity = generator.CreateClassProxy<Class5_test1>(interceptor);
            //SensorRecordService entity = generator.CreateClassProxy<SensorRecordService>(interceptor);


            

            DateTime beforDT1 = DateTime.Now;//开始时间     
            try
            {
                entity.test1();
                //entity.DealWithSensorRecord(74619, 75705);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            MethodOperationInfo.Show();

            TimeSpan ts1 = DateTime.Now.Subtract(beforDT1);
            Console.WriteLine($"总耗时:{ts1.TotalSeconds.ToString()}秒  或  {ts1.TotalMinutes.ToString("f3")}分");
            Console.WriteLine("操作完成!");
            Console.ReadLine();
        }

    }
    public class Class5_test1
    {
        public virtual void test1()
        {
            System.Threading.Thread.Sleep(1000 * 1);
            int num = 0;
            for (int i = 0; i < 10000; i++)
            {
                num += 1;
            }
            test1(1);
            test1(1, 2);
            test1(1, "");
        }
        public virtual void test1(int i)
        {
        }
        public virtual void test1(int i, int j)
        {
        }
        public virtual void test1(int i, string j)
        {
        }
    }

    //拦截器
    public class CallingLogInterceptor : IInterceptor
    {
        private DateTime dt { get; set; }
        private TimeSpan ts { get; set; }

        //方法执行前
        private void PreProceed(IInvocation invocation)
        {
            dt = DateTime.Now;
        }
        //方法执行后
        private void PostProceed(IInvocation invocation)
        {
            ts = DateTime.Now - dt;
            //Console.Write($"类名:{invocation.TargetType} 方法名:{invocation.Method.Name} 耗时:{ts.TotalMilliseconds}毫秒
");

            var arr = invocation.Arguments;

            MethodOperationInfo.Add(invocation, ts.TotalMilliseconds);
        }
        //拦截
        public void Intercept(IInvocation invocation)
        {
            this.PreProceed(invocation);
            invocation.Proceed();//调用
            this.PostProceed(invocation);
        }
    }

    public class MethodOperationInfo
    {
        public string NameSpaceName { get; set; }
        public string ClassName { get; set; }
        public string MethodName { get; set; }
        public string Parameters { get; set; }
        public double TotalMilliseconds { get; set; }
        public int Num { get; set; }



        public static List<MethodOperationInfo> list = new List<MethodOperationInfo>();
        public static void Add(IInvocation invocation, double TotalMilliseconds)
        {
            string Parameters = "";
            if ((invocation.Arguments != null) && (invocation.Arguments.Length > 0))
            {
                Parameters = JsonConvert.SerializeObject(invocation.Arguments);
            }

            string MethodName = GetMethodNameHavePara(invocation.Method);
            list.Add(new MethodOperationInfo
            {
                MethodName = MethodName,
                Parameters = Parameters,
                TotalMilliseconds = TotalMilliseconds,
                Num = 1
            });
        }


        public static string GetMethodNameHavePara(MethodInfo mInfo)
        {
            string str = "";
            //str += GetSameLenString(mInfo.ReflectedType.FullName, 50);//类名(含命名空间)

            var pInfos = mInfo.GetParameters();
            str += mInfo.Name;
            str += "(";
            for (int j = 0; j < pInfos.Length; j++)
            {
                var p = pInfos[j];
                string pTypeName = $"{p.ParameterType.ToString()}, ";
                if (p.ParameterType.IsGenericType && (p.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>)))
                {
                    pTypeName = $"{Nullable.GetUnderlyingType(p.ParameterType).Name}?, ";
                }
                str += pTypeName;
            }
            str = str.TrimEnd(' ').TrimEnd(',');
            str += ")";

            return str;
        }
        public static string GetSameLenString(object obj, int len, bool afterFill = true)
        {
            string name = obj.ToString();
            int count = len - name.Length;

            if (afterFill)
            {
                for (int i = 0; i < count; i++)
                {
                    name += " ";
                }
                return name;

            }
            else
            {
                string value = "";
                for (int i = 0; i < count; i++)
                {
                    value += " ";
                }
                value += name;
                return value;
            }
        }


        


        public static void Show()
        {
            StringBuilder sb = new StringBuilder();


            //方法耗时统计
            Dictionary<string, MethodOperationInfo> dic = new Dictionary<string, MethodOperationInfo>();
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine($"处理数据-当前行:{list.Count - i}");
                var item = list[i];
                string MethodName = item.MethodName;
                double TotalMilliseconds = item.TotalMilliseconds;

                if (dic.ContainsKey(MethodName))
                {
                    dic[MethodName].TotalMilliseconds += TotalMilliseconds;
                    dic[MethodName].Num += 1;
                }
                else
                {
                    dic.Add(MethodName, new MethodOperationInfo
                    {
                        MethodName = MethodName,
                        TotalMilliseconds = TotalMilliseconds,
                        Num = 1
                    });
                }
            }

            //日志
            string str = "";
            double Total_Milliseconds = 0;
            foreach (var item in dic)
            {
                Total_Milliseconds += item.Value.TotalMilliseconds;
                str += $"方法:{GetSameLenString(item.Key, 80)}     ";
                str += $"次数:{GetSameLenString(item.Value.Num, 10)}     ";
                str += $"耗时:{GetSameLenString(item.Value.TotalMilliseconds, 10, false) }毫秒     ";
                str += $"
";
            }
            str += "
";
            str += "
";
            str += $"总耗时:{Total_Milliseconds}毫秒    ";
            str += $"{Total_Milliseconds / 1000}秒    ";
            str += $"{(Total_Milliseconds / 1000 / 60).ToString("f2")}分钟    ";
            str += $"当前时间:{DateTime.Now}    ";
            str += "
";
            str += "
";
            str += "
";
            sb.Append(str);



            //每个方法 每次的 单独耗时
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine($"处理数据-当前行:{list.Count - i}");
                var item = list[i];
                sb.Append($"方法:{GetSameLenString(item.MethodName, 80)}     ");
                sb.Append($"次数:{GetSameLenString(item.Num, 10)}     ");
                sb.Append($"耗时:{GetSameLenString(item.TotalMilliseconds, 10, false) }毫秒     ");
                sb.Append($"参数:{GetSameLenString(item.Parameters, 50)}     ");
                sb.Append($"
");
            }


            System.IO.File.WriteAllText("1.txt", sb.ToString());
            Console.WriteLine("完成!");
        }

        public static void Show2()
        {
            StringBuilder sb = new StringBuilder();
            Dictionary<string, MethodOperationInfo> dic = new Dictionary<string, MethodOperationInfo>();

            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine($"处理数据-当前行:{list.Count - i}");
                var item = list[i];

                //每个方法每次的耗时
                sb.Append($"方法:{GetSameLenString(item.MethodName, 80)}     ");
                sb.Append($"次数:{GetSameLenString(item.Num, 10)}     ");
                sb.Append($"耗时:{GetSameLenString(item.TotalMilliseconds, 10, false) }毫秒     ");
                sb.Append($"参数:{GetSameLenString(item.Parameters, 50)}     ");
                sb.Append($"
");

                //每个方法的总耗时
                string MethodName = item.MethodName;
                double TotalMilliseconds = item.TotalMilliseconds;
                if (dic.ContainsKey(MethodName))
                {
                    dic[MethodName].TotalMilliseconds += TotalMilliseconds;
                    dic[MethodName].Num += 1;
                }
                else
                {
                    dic.Add(MethodName, new MethodOperationInfo
                    {
                        MethodName = MethodName,
                        TotalMilliseconds = TotalMilliseconds,
                        Num = 1
                    });
                }
            }

            //日志
            string str = "";
            double Total_Milliseconds = 0;
            str += "《每个方法的总耗时》
";
            foreach (var item in dic)
            {
                Total_Milliseconds += item.Value.TotalMilliseconds;
                str += $"方法:{GetSameLenString(item.Key, 80)}     ";
                str += $"次数:{GetSameLenString(item.Value.Num, 10)}     ";
                str += $"耗时:{GetSameLenString(item.Value.TotalMilliseconds, 10, false) }毫秒     ";
                str += $"
";
            }
            str += "
";
            str += $"《总耗时》:{Total_Milliseconds}毫秒    ";
            str += $"{Total_Milliseconds / 1000}秒    ";
            str += $"{(Total_Milliseconds / 1000 / 60).ToString("f2")}分钟    ";
            str += $"当前时间:{DateTime.Now}    ";
            str += "

";

            str += "《每个方法每次的耗时》
";
            sb.Insert(0, str);

            System.IO.File.WriteAllText("1.txt", sb.ToString());
            Console.WriteLine("完成!");
        }
    }



    #region old

    //public class MethodOperationInfo
    //{
    //    public string ClassName { get; set; }
    //    public string MethodName { get; set; }
    //    public double TotalMilliseconds { get; set; }
    //    public int Num { get; set; }



    //    public static Dictionary<string, MethodOperationInfo> dic = new Dictionary<string, MethodOperationInfo>();
    //    public static void Add(string MethodName, double TotalMilliseconds)
    //    {
    //        if (dic.ContainsKey(MethodName))
    //        {
    //            dic[MethodName].TotalMilliseconds += TotalMilliseconds;
    //            dic[MethodName].Num += 1;
    //        }
    //        else
    //        {
    //            dic.Add(MethodName, new MethodOperationInfo
    //            {
    //                MethodName = MethodName,
    //                TotalMilliseconds = TotalMilliseconds,
    //                Num = 1
    //            });
    //        }
    //    }
    //    public static void Add(MethodInfo mInfo, double TotalMilliseconds)
    //    {
    //        string MethodName = GetMethodNameHavePara(mInfo);
    //        if (dic.ContainsKey(MethodName))
    //        {
    //            dic[MethodName].TotalMilliseconds += TotalMilliseconds;
    //            dic[MethodName].Num += 1;
    //        }
    //        else
    //        {
    //            dic.Add(MethodName, new MethodOperationInfo
    //            {
    //                MethodName = MethodName,
    //                TotalMilliseconds = TotalMilliseconds,
    //                Num = 1
    //            });
    //        }
    //    }
    //    public static void Add(IInvocation invocation, double TotalMilliseconds)
    //    {
    //        string MethodName = GetMethodNameHavePara(invocation.Method);
    //        if (dic.ContainsKey(MethodName))
    //        {
    //            dic[MethodName].TotalMilliseconds += TotalMilliseconds;
    //            dic[MethodName].Num += 1;
    //        }
    //        else
    //        {
    //            dic.Add(MethodName, new MethodOperationInfo
    //            {
    //                MethodName = MethodName,
    //                TotalMilliseconds = TotalMilliseconds,
    //                Num = 1
    //            });
    //        }
    //    }



    //    public static string GetMethodNameHavePara(MethodInfo mInfo)
    //    {
    //        string str = "";
    //        //str += GetSameLenString(mInfo.ReflectedType.FullName, 50);//类名(含命名空间)

    //        var pInfos = mInfo.GetParameters();
    //        str += mInfo.Name;
    //        str += "(";
    //        for (int j = 0; j < pInfos.Length; j++)
    //        {
    //            var p = pInfos[j];
    //            string pTypeName = $"{p.ParameterType.ToString()}, ";
    //            if (p.ParameterType.IsGenericType && (p.ParameterType.GetGenericTypeDefinition() == typeof(Nullable<>)))
    //            {
    //                pTypeName = $"{Nullable.GetUnderlyingType(p.ParameterType).Name}?, ";
    //            }
    //            str += pTypeName;
    //        }
    //        str = str.TrimEnd(' ').TrimEnd(',');
    //        str += ")";

    //        return str;
    //    }
    //    public static string GetSameLenString(object obj, int len, bool afterFill = true)
    //    {
    //        string name = obj.ToString();
    //        int count = len - name.Length;

    //        if (afterFill)
    //        {
    //            for (int i = 0; i < count; i++)
    //            {
    //                name += " ";
    //            }
    //            return name;

    //        }
    //        else
    //        {
    //            string value = "";
    //            for (int i = 0; i < count; i++)
    //            {
    //                value += " ";
    //            }
    //            value += name;
    //            return value;
    //        }
    //    }


    //    public static void Show()
    //    {
    //        string str = "";
    //        double TotalMilliseconds = 0;

    //        foreach (var item in dic)
    //        {
    //            TotalMilliseconds += item.Value.TotalMilliseconds;
    //            str += $"方法:{GetSameLenString(item.Key, 80)}     ";
    //            str += $"次数:{GetSameLenString(item.Value.Num, 10)}     ";
    //            str += $"耗时:{GetSameLenString(item.Value.TotalMilliseconds, 10, false) }毫秒     ";
    //            str += $"
";
    //        }

    //        str += "
";
    //        str += "
";
    //        str += $"总耗时:{TotalMilliseconds}毫秒    ";
    //        str += $"{TotalMilliseconds / 1000}秒    ";
    //        str += $"{(TotalMilliseconds / 1000 / 60).ToString("f2")}分钟    ";
    //        str += $"当前时间:{DateTime.Now}    ";
    //        str += "
";

    //        System.IO.File.WriteAllText("1.txt", str);

    //        Console.WriteLine("--------------------------

");
    //        Console.WriteLine(str);
    //    }

    //} 
    #endregion
}
View Code

截图1:

截图2:

原文地址:https://www.cnblogs.com/guxingy/p/10132062.html