欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

获取C#中方法的执行时间及其代码注入

程序员文章站 2022-05-14 08:26:43
在优化C#代码或对比某些API的效率时,通常需要测试某个方法的运行时间,可以通过DateTime来统计指定方法的执行时间,也可以使用命名空间System.Diagnostics中封装了高精度计时器QueryPerformanceCounter方法的Stopwatch类来统计指定方法的执行时间: 1. ......

  在优化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代码:

获取C#中方法的执行时间及其代码注入

  代码注入后il代码:

获取C#中方法的执行时间及其代码注入

  代码注入后运行结果:

获取C#中方法的执行时间及其代码注入

 

 


 如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的认可是我写作的最大动力!

作者:minotauros
出处:

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。