在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( * );
int num = ;
for (int i = ; i < ; i++)
{
num += ;
}
test1();
test1(, );
test1(, "");
}
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}毫秒\r\n"); 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 > ))
{
Parameters = JsonConvert.SerializeObject(invocation.Arguments);
} string MethodName = GetMethodNameHavePara(invocation.Method);
list.Add(new MethodOperationInfo
{
MethodName = MethodName,
Parameters = Parameters,
TotalMilliseconds = TotalMilliseconds,
Num =
});
} 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 = ; 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 = ; i < count; i++)
{
name += " ";
}
return name; }
else
{
string value = "";
for (int i = ; 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 = ; 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 += ;
}
else
{
dic.Add(MethodName, new MethodOperationInfo
{
MethodName = MethodName,
TotalMilliseconds = TotalMilliseconds,
Num =
});
}
} //日志
string str = "";
double Total_Milliseconds = ;
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 += $"\r\n";
}
str += "\r\n";
str += "\r\n";
str += $"总耗时:{Total_Milliseconds}毫秒 ";
str += $"{Total_Milliseconds / 1000}秒 ";
str += $"{(Total_Milliseconds / 1000 / 60).ToString("f2")}分钟 ";
str += $"当前时间:{DateTime.Now} ";
str += "\r\n";
str += "\r\n";
str += "\r\n";
sb.Append(str); //每个方法 每次的 单独耗时
for (int i = ; 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($"\r\n");
} 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 = ; 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($"\r\n"); //每个方法的总耗时
string MethodName = item.MethodName;
double TotalMilliseconds = item.TotalMilliseconds;
if (dic.ContainsKey(MethodName))
{
dic[MethodName].TotalMilliseconds += TotalMilliseconds;
dic[MethodName].Num += ;
}
else
{
dic.Add(MethodName, new MethodOperationInfo
{
MethodName = MethodName,
TotalMilliseconds = TotalMilliseconds,
Num =
});
}
} //日志
string str = "";
double Total_Milliseconds = ;
str += "《每个方法的总耗时》\r\n";
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 += $"\r\n";
}
str += "\r\n";
str += $"《总耗时》:{Total_Milliseconds}毫秒 ";
str += $"{Total_Milliseconds / 1000}秒 ";
str += $"{(Total_Milliseconds / 1000 / 60).ToString("f2")}分钟 ";
str += $"当前时间:{DateTime.Now} ";
str += "\r\n\r\n"; str += "《每个方法每次的耗时》\r\n";
sb.Insert(, 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 += $"\r\n";
// } // str += "\r\n";
// str += "\r\n";
// str += $"总耗时:{TotalMilliseconds}毫秒 ";
// str += $"{TotalMilliseconds / 1000}秒 ";
// str += $"{(TotalMilliseconds / 1000 / 60).ToString("f2")}分钟 ";
// str += $"当前时间:{DateTime.Now} ";
// str += "\r\n"; // System.IO.File.WriteAllText("1.txt", str); // Console.WriteLine("--------------------------\r\n\r\n");
// Console.WriteLine(str);
// } //}
#endregion
}

截图1:

截图2:

C# 监测每个方法的执行次数和占用时间(测试2)的更多相关文章

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

    原文:http://www.cnblogs.com/RicCC/archive/2010/03/15/castle-dynamic-proxy.html 在Nuget引用 Castle.Dynamic ...

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

    今天也要做这个功能,就百度一下,结果搜索到了自己的文章.一开始还没注意,当看到里面的一个注释的方法时,一开始还以为自己复制错了代码,结果仔细一看网页的文章,我去,原来是自己写的,写的确实不咋地. 把自 ...

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

    在Nuget引用 Castle.DynamicProxy 和 Newtonsoft.Json 这个 原文:http://www.cnblogs.com/RicCC/archive/2010/03/15 ...

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

    又找到了一个bug 测试的类: public class Class11_1 { public virtual List<int> test2_1(List<tb_SensorRec ...

  5. 事件之onTouch方法的执行过程 及和 onClick执行发生冲突的解决办法

    转载:http://blog.csdn.net/jiangwei0910410003/article/details/17504315#quote 博主推荐: 风萧兮兮易水寒,“天真”一去兮不复还.如 ...

  6. Android中onTouch方法的执行过程以及和onClick执行发生冲突的解决办法

    $*********************************************************************************************$ 博主推荐 ...

  7. ORACLE查看SQL的执行次数/频率

    在ORACLE数据库应用调优中,一个SQL的执行次数/频率也是常常需要关注的,因为某个SQL执行太频繁,要么是由于应用设计有缺陷,需要在业务逻辑上做出优化处理,要么是业务特殊性所导致.如果执行频繁的S ...

  8. PLSQL_查询SQL的执行次数和频率(案例)

    2014-12-25 Created By BaoXinjian

  9. PLSQL_监控有些SQL的执行次数和频率

    原文:PLSQL_监控有些SQL的执行次数和频率 2014-12-25 Created By 鲍新建

随机推荐

  1. Html5——音频标签使用

    Ogg 文件,适用于Firefox.Opera 以及 Chrome 浏览器. 要确保适用于 Safari 浏览器,音频文件必须是 MP3 或 Wav 类型. audio 元素允许多个 source 元 ...

  2. Centos下安装Docker集群管理工具Shipyard

    一. Docker Shipyard是什么 ? shipyard是一个开源的docker管理平台,其特性主要包括: 支持镜像管理.容器管理. 支持控制台命令 容器资源消耗监控 支持集群swarm,可以 ...

  3. 为什么TCP比UDP可靠真正原因,以及并发编程的基础问题

    一  为什么TCP协议比UDP协议传输数据可靠: 我们知道在传输数据的时候,数据是先存在操作系统的缓存中,然后发送给客户端,在客户端也是要经过客户端的操作系统的,因为这个过程涉及到计算机硬件,也就是物 ...

  4. Python列表生成式和生成器

    [1]列表生成器:列表生成式就是一个用来生成列表的特定语法形式的表达式. 1.基础语句结构:[exp for iter_var in iterable例如:a=[f(x) for x in range ...

  5. gulp安装,淘宝镜像

    命令:express -e ./ express表示安装express -e表示使用ejs作为模板 ./表示当前目录中 (使用上面的命令之前我们应该使用npm安装express框架 sudo npm ...

  6. elastalert新增自定义警告推送

    举例,博主公司有自己的内部通讯工具(类似QQ),接下来用IM代称该工具.于是希望elastalert的警告推送可以支持IM的公众号群发功能. 等博主这个月知识库写了再来补充hah

  7. 踩过的坑:InteliIJ IDEA 打开的项目突然左侧目录结构消失了,如何处理?

    试了很多的办法,删除项目,然后重新从git下载,再导入项目,但是对于暂存未上传到git的文件也会被一并删除,这样就亏大发了 之前一直没有找到解决办法,这里记一下终身有效的办法,并且比较好操作 按下列步 ...

  8. 背景图片的移动----background-attach-----background-repeat

    background-repeat:默认是平铺的,也即是还有空间的话将一张接着一张显示 设置为 no-repeat  就最多显示一张 background-attachment:设置是否固定图片,在有 ...

  9. jq 上传下载进度条

    里面只演示了下载的,挂载的是我的七牛服务器上的内容,上传事件和下载是一模一样的,为了大家不乱上传东西到我的服务器,而且我的服务器容量也不大,这里只展示了下载.代码: <!DOCTYPE html ...

  10. winform 布局、容器

    一.布局 属性:1.Anchor:  绑定控件到容器边缘位置保持不变 注:四周全锁定时控件随界面变化时变大 2.Dock:绑定到容器的边缘 注:下控件到边需先将下控件定义到边再将左右控件新建.到边 3 ...