欧美一区二区三区老妇人-欧美做爰猛烈大尺度电-99久久夜色精品国产亚洲a-亚洲福利视频一区二区

怎么獲取C#中方法的執(zhí)行時間以及其代碼注入-創(chuàng)新互聯(lián)

小編給大家分享一下怎么獲取C#中方法的執(zhí)行時間以及其代碼注入,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

創(chuàng)新互聯(lián)公司專注于企業(yè)網(wǎng)絡(luò)營銷推廣、網(wǎng)站重做改版、涼山州網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5頁面制作、購物商城網(wǎng)站建設(shè)、集團公司官網(wǎng)建設(shè)、外貿(mào)網(wǎng)站制作、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為涼山州等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。

前言

在優(yōu)化C#代碼或?qū)Ρ饶承〢PI的效率時,通常需要測試某個方法的運行時間,可以通過DateTime來統(tǒng)計指定方法的執(zhí)行時間,也可以使用命名空間System.Diagnostics中封裝了高精度計時器QueryPerformanceCounter方法的Stopwatch類來統(tǒng)計指定方法的執(zhí)行時間:

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()方法的運行毫秒數(shù)

//重置計時器
stopwatch.Restart(); //此處可以使用stopwatch.Reset(); stopwatch.Start();組合代替

MyFunc();

stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds); //本次MyFunc()方法的運行毫秒數(shù)

以上兩種辦法都可以達到獲取方法執(zhí)行時間的目的,但是在需要對整個項目中的方法都進行監(jiān)測用時時,除了使用性能分析工具,我們還可以通過代碼注入的方式給程序集中每一個方法加入計時器;

通過命名空間System.Reflection.Emit中的類可以動態(tài)的創(chuàng)建程序集、類型和成員,通常類庫Mono.Cecil可以動態(tài)讀取并修改已經(jīng)生成的IL文件,這種在不修改源代碼的情況下給程序集動態(tài)添加功能的技術(shù)稱為面向切面編程(AOP);

這里給出了一個注入使用Stopwatch來檢測方法執(zhí)行時間的代碼,這里的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命令即可編譯出可執(zhí)行程序,將目標程序集文件拖入到該應(yīng)用程序即可在程序集目錄導(dǎo)出注入代碼后的程序集文件,經(jīng)過測試,包括方法擁有返回值和方法的參數(shù)列表中包含out和ref參數(shù)等情況都不會對運行結(jié)果產(chǎn)生影響;

示例:

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#中方法的執(zhí)行時間以及其代碼注入

代碼注入后IL代碼:

怎么獲取C#中方法的執(zhí)行時間以及其代碼注入

代碼注入后運行結(jié)果:

 怎么獲取C#中方法的執(zhí)行時間以及其代碼注入

看完了這篇文章,相信你對“怎么獲取C#中方法的執(zhí)行時間以及其代碼注入”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注創(chuàng)新互聯(lián)成都網(wǎng)站設(shè)計公司行業(yè)資訊頻道,感謝各位的閱讀!

另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。

名稱欄目:怎么獲取C#中方法的執(zhí)行時間以及其代碼注入-創(chuàng)新互聯(lián)
URL地址:http://chinadenli.net/article6/doshog.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供域名注冊、微信公眾號、外貿(mào)建站用戶體驗、網(wǎng)站營銷、電子商務(wù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

搜索引擎優(yōu)化