如何獲取C#中方法的執(zhí)行時間以及其代碼注入詳解
前言
在優(yōu)化C#代碼或?qū)Ρ饶承〢PI的效率時,通常需要測試某個方法的運(yùn)行時間,可以通過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()方法的運(yùn)行毫秒數(shù) //重置計時器 stopwatch.Restart(); //此處可以使用stopwatch.Reset(); stopwatch.Start();組合代替 MyFunc(); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); //本次MyFunc()方法的運(yùn)行毫秒數(shù)
以上兩種辦法都可以達(dá)到獲取方法執(zhí)行時間的目的,但是在需要對整個項目中的方法都進(jìn)行監(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進(jìn)行安裝:
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í)行程序,將目標(biāo)程序集文件拖入到該應(yīng)用程序即可在程序集目錄導(dǎo)出注入代碼后的程序集文件,經(jīng)過測試,包括方法擁有返回值和方法的參數(shù)列表中包含out和ref參數(shù)等情況都不會對運(yùn)行結(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代碼:
代碼注入后IL代碼:
代碼注入后運(yùn)行結(jié)果:
總結(jié):
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對我們的支持。
欄 目:C#教程
本文標(biāo)題:如何獲取C#中方法的執(zhí)行時間以及其代碼注入詳解
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/5019.html
您可能感興趣的文章
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并打開的方法
- 01-10C#實現(xiàn)Winform中打開網(wǎng)頁頁面的方法
- 01-10C#實現(xiàn)由四周向中心縮小的窗體退出特效
- 01-10Extjs4如何處理后臺json數(shù)據(jù)中日期和時間
- 01-10C#獲取進(jìn)程或線程相關(guān)信息的方法
- 01-10C#調(diào)用dos窗口獲取相關(guān)信息的方法
- 01-10C#中DataGridView常用操作實例小結(jié)
- 01-10C#編程獲取資源文件中圖片的方法
- 01-10C#獲取任務(wù)欄顯示進(jìn)程的方法
- 01-10asp.net中XML如何做增刪改查操作


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 01-11ajax實現(xiàn)頁面的局部加載
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10C#中split用法實例總結(jié)
- 04-02jquery與jsp,用jquery
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10delphi制作wav文件的方法