当前位置: 移动技术网 > IT编程>开发语言>c# > 如何获取C#中方法的执行时间以及其代码注入详解

如何获取C#中方法的执行时间以及其代码注入详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

前言

在优化c#代码或对比某些api的效率时,通常需要测试某个方法的运行时间,可以通过datetime来统计指定方法的执行时间,也可以使用命名空间system.diagnostics中封装了高精度计时器queryperformancecounter方法的stopwatch类来统计指定方法的执行时间:

1.使用datetime方法:

datetime datetime = datetime.now;

myfunc();

console.writeline((datetime.now - datetime).totalmilliseconds);

2.使用stopwatch方式:

stopwatch stopwatch = new stopwatch();
stopwatch.start();
myfunc();

stopwatch.stop();

console.writeline(stopwatch.elapsedmilliseconds); //本次myfunc()方法的运行毫秒数

//重置计时器
stopwatch.restart(); //此处可以使用stopwatch.reset(); stopwatch.start();组合代替

myfunc();

stopwatch.stop();
console.writeline(stopwatch.elapsedmilliseconds); //本次myfunc()方法的运行毫秒数

以上两种办法都可以达到获取方法执行时间的目的,但是在需要对整个项目中的方法都进行监测用时时,除了使用性能分析工具,我们还可以通过代码注入的方式给程序集中每一个方法加入计时器;

通过命名空间system.reflection.emit中的类可以动态的创建程序集、类型和成员,通常类库mono.cecil可以动态读取并修改已经生成的il文件,这种在不修改源代码的情况下给程序集动态添加功能的技术称为面向切面编程(aop);

这里给出了一个注入使用stopwatch来检测方法执行时间的代码,这里的mono.cecil类库可以通过nuget进行安装:

using system;
using system.io;
using system.linq;
using system.diagnostics;
using mono.cecil;
using mono.cecil.cil;
using mono.collections.generic;
static void main(string[] args)
 {
 for (int i = 0; i < args.length; i++)
 {
 filestream filestream = new filestream(args[i], filemode.open);
 if (filestream != null)
 {
 assemblydefinition ad = assemblydefinition.readassembly(filestream);
 moduledefinition md = ad.mainmodule;
 collection<typedefinition> typedefinition = md.types;
 foreach (typedefinition type in typedefinition)
 {
  if (type.isclass)
  {
  foreach (methoddefinition method in type.methods)
  {
  if (method.ispublic && !method.isconstructor)
  {
  ilprocessor il = method.body.getilprocessor();
  typereference stt = md.importreference(typeof(stopwatch));
  variabledefinition stv = new variabledefinition(stt);
  method.body.variables.add(stv);
  instruction first = method.body.instructions.first();
  il.insertbefore(first, il.create(opcodes.newobj,                       md.importreference(typeof(stopwatch).getconstructor(new type[] { }))));
  il.insertbefore(first, il.create(opcodes.stloc_s, stv));
  il.insertbefore(first, il.create(opcodes.ldloc_s, stv));
  il.insertbefore(first, il.create(opcodes.callvirt,                      md.importreference(typeof(stopwatch).getmethod("start"))));

  instruction @return = method.body.instructions.last();
  il.insertbefore(@return, il.create(opcodes.ldloc_s, stv));
  il.insertbefore(@return, il.create(opcodes.callvirt,                       md.importreference(typeof(stopwatch).getmethod("stop"))));

  il.insertbefore(@return, il.create(opcodes.ldstr, $"{method.fullname} run time: "));
  il.insertbefore(@return, il.create(opcodes.ldloc_s, stv));
  il.insertbefore(@return, il.create(opcodes.callvirt,                       md.importreference(typeof(stopwatch).getmethod("get_elapsedmilliseconds"))));
  il.insertbefore(@return, il.create(opcodes.box, md.importreference(typeof(long))));
  il.insertbefore(@return, il.create(opcodes.call,                       md.importreference(typeof(string).getmethod("concat", new type[] { typeof(object), typeof(object) }))));
  il.insertbefore(@return, il.create(opcodes.call,                       md.importreference(typeof(console).getmethod("writeline", new type[] { typeof(string) }))));
  }
  }
  }
 }
 fileinfo fileinfo = new fileinfo(args[i]);
 string filename = fileinfo.name;
 int pointindex = filename.lastindexof('.');
 string frontname = filename.substring(0, pointindex);
 string backname = filename.substring(pointindex, filename.length - pointindex);
 string writefilepath = path.combine(fileinfo.directory.fullname, frontname + "_inject" + backname);
 ad.write(writefilepath);
 console.writeline($"success! output path: {writefilepath}");
 filestream.dispose();
 }
 }
 console.read();
 }

完整的项目传到了github上=>injectionstopwatchcode (),下载项目后,通过dotnet build命令即可编译出可执行程序,将目标程序集文件拖入到该应用程序即可在程序集目录导出注入代码后的程序集文件,经过测试,包括方法拥有返回值和方法的参数列表中包含out和ref参数等情况都不会对运行结果产生影响;

示例:

using system;

public class myclass
{
 public void myfunc()
 {
 int num = 1;
 for (int i = 0; i < int.maxvalue; i++)
 {
 num++;
 }
 }
}
public class program
{
 public static void main(string[] args)
 {
 myclass myobj = new myclass();
 myobj.myfunc();
 console.read();
 }
}

原始il代码:

代码注入后il代码:

代码注入后运行结果:

 

 总结:

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网