A_05 效能調優:採用BenchmarkDotNet對c#程式碼進行基準測試,
阿新 • • 發佈:2021-07-28
1、BenchmarkDotNet
BenchmarkDotNet可幫助將方法轉換為基準、跟蹤其效能並共享可重複的測量實驗。簡而言之,採用BenchmarkDotNet可以對方法或者程式碼塊進行基準測試,可以對程式碼進行調優,並且對程式碼進行侵入性很低。可以在同一環境下測試不同的方法效能;可以在不同平臺(.net core、.net framework)測試相同的程式碼,達到測試不同平臺的效能。
2、Demo操作
(1)測試結果重要引數說明:
Method:測試的方法或程式碼;
Mean:測試方法平均用時;
Allocated:測試時需要分配的記憶體
(2)程式碼
對lua指令碼直譯器庫NLua和MoonSharp進行基準測試,用於比較那個效能更加優秀
using BenchmarkDotNet.Attributes; using MoonSharp.Interpreter; using NLua; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BenchmarkTestDemo { /// <summary> /// Lua指令碼效能基準測試 /// </summary> [MemoryDiagnoser] public class LuaScriptTestContext { [Benchmark]public void NLua() { Lua state = new Lua(); string hex1 = "001100220044555"; string scriptCode = @" function operate(hexArr,executeCode) if(executeCode==""read"") then local index=1 local string=string temp='""temp""' humi='""humi""' local tmp_valu=string.sub(hexArr,3,4) local humi_valu=string.sub(hexArr,7,8) local result = string.format(""{%s:%d,%s:%d}"",temp,tonumber(tmp_valu,16),humi,tonumber(humi_valu,16)) return result else return """" end end"; state.DoString(scriptCode); var scriptFunc = state["operate"] as LuaFunction; var res = scriptFunc.Call(hex1, "read").First(); } [Benchmark] public void MoonSharp() { string hex1 = "001100220044555"; string scriptCode = @" function operate(hexArr,executeCode) if(executeCode==""read"") then local index=1 local string=string temp='""temp""' humi='""humi""' local tmp_valu=string.sub(hexArr,3,4) local humi_valu=string.sub(hexArr,7,8) local result = string.format(""{%s:%d,%s:%d}"",temp,tonumber(tmp_valu,16),humi,tonumber(humi_valu,16)) return result else return """" end end"; Script script = new Script(); script.DoString(scriptCode); var res = script.Call(script.Globals["operate"], hex1, "read").String; } } }
using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; using System; namespace BenchmarkTestDemo { class Program { static void Main(string[] args) { Summary summary = BenchmarkRunner.Run<LuaScriptTestContext>(); Console.Read(); } } }
(3)測試報告
從測試報告可以看出,NLua直譯器庫效能更加優秀