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

  在优化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命令即可编译出可执行程序,将目标程序集文件拖入到该应用程序即可在程序集目录导出注入代码后的程序集文件;



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

作者:Minotauros
出处:https://www.cnblogs.com/minotauros/

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

原文地址:https://www.cnblogs.com/minotauros/p/9930163.html

时间: 2024-08-29 19:44:09

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

父窗口中获取iframe中的元素

js 在父窗口中获取iframe中的元素 1. Js代码   格式:window.frames["iframe的name值"].document.getElementById("iframe中控件的ID").click(); 实例:window.frames["ifm"].document.getElementById("btnOk").click(); 2. Java代码   格式: var obj=document.get

60秒验证码倒计时js代码 js样式代码 方块上下左右随机移动(定时器) js中获取元素的方法 js中表单提交

60秒验证码倒计时js代码 <script type="text/javascript"> var countdown=60; function settime(val) { if (countdown == 0) { //removeAttribute() 方法删除指定的属性. disabled属性规定应该禁用 input 元素. val.removeAttribute("disabled"); val.value="免费获取验证码"

JS获取URL中参数值(QueryString)的4种方法

在某书上看到这道题目,查找解题思路后做了部分解析,如有错误请指正 方法一:正则法 代码如下: function getQueryString(name) {    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i'); //匹配指定name的QueryString    var r = window.location.search.substr(1).match(reg); //window.location.sea

Android中WebView获取网页中标题 ,内容, 图片的方法

如题,在Android中WebView获取网页中标题 ,内容, 图片的方法 首先是获取标题,在new WebChromeClient(){}中重写onReceivedTitle()方法 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); // loge.e("__页面标题__"+title); } 获取内容,是参考的这边的 http

spring mvc中,如何在 Java 代码里,获取 国际化 内容

首先,在Spring的application.xml中定义 <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <!-- 国际化信息所在的文件名 --> <property name="basename" value="messages/messages"

dedecms获取文章中的图片代码

1.在 /include/common.func.php 文件底部加入以下代码 /** * getArcImages 获取文章中的图片 * $id 文章ID * $num 要获取的图片数量 默认为4张 */ function getArcImages($id,$num=4){ global $dsql; $row = $dsql->GetOne("SELECT * FROM dede_addonarticle WHERE aid= $id"); $content = $row['

JS获取URL中参数值(QueryString)的4种方法分享

http://www.jb51.net/article/48942.htm JS获取URL中参数值(QueryString)的4种方法分享 作者: 字体:[增加 减小] 类型:转载 今天碰到要在一个页面获取另外一个页面url传过来的参数,一开始很本能的想到了用 split("?")这样一步步的分解出需要的参数.后来想了一下,肯定会有更加简单的方法的!所以在网上找到了几个很又简单实用的方法,mark下. 方法一:正则法 复制代码 代码如下: function getQueryString

Spring中如何获取request的方法汇总及其线程安全性分析

前言 本文将介绍在Spring MVC开发的web系统中,获取request对象的几种方法,并讨论其线程安全性.下面话不多说了,来一起看看详细的介绍吧. 概述 在使用Spring MVC开发Web系统时,经常需要在处理请求时使用request对象,比如获取客户端ip地址.请求的url.header中的属性(如cookie.授权信息).body中的数据等.由于在Spring MVC中,处理请求的Controller.Service等对象都是单例的,因此获取request对象时最需要注意的问题,便是

【Java必修课】通过Value获取Map中的键值Key的四种方法

1 简介 我们都知道Map是存放键值对<Key,Value>的容器,知道了Key值,使用方法Map.get(key)能快速获取Value值.然而,有的时候我们需要反过来获取,知道Value值,求Key值. 本文将用实例介绍四种方法,通过传入Value值,获取得到Key值. 2 四种方法 2.1 循环法 循环法就是通过遍历Map里的Entry,一个个比较,把符合条件的找出来.会有三种情况: (1)找到一个值 (2)找到多个值 (3)找不到 具体代码如下: @Test public void lo