AddBenchmark.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System.Reflection;
  2. using BenchmarkDotNet.Attributes;
  3. using Lua;
  4. using Lua.Standard;
  5. using MoonSharp.Interpreter;
  6. [Config(typeof(BenchmarkConfig))]
  7. public class AddBenchmark
  8. {
  9. BenchmarkCore core = new();
  10. LuaValue[] buffer = new LuaValue[1];
  11. public static double Add(double x, double y)
  12. {
  13. return x + y;
  14. }
  15. [IterationSetup]
  16. public void Setup()
  17. {
  18. core = new();
  19. core.Setup("add.lua");
  20. core.LuaCSharpState.OpenStandardLibraries();
  21. core.LuaCSharpState.Environment["add"] = new LuaFunction("add", (context, ct) =>
  22. {
  23. var a = context.GetArgument<double>(0);
  24. var b = context.GetArgument<double>(1);
  25. return new(context.Return(a + b));
  26. });
  27. core.MoonSharpState.Globals["add"] = (Func<double, double, double>)Add;
  28. core.NLuaState.RegisterFunction("add", typeof(AddBenchmark).GetMethod(nameof(Add), BindingFlags.Static | BindingFlags.Public));
  29. }
  30. [IterationCleanup]
  31. public void Cleanup()
  32. {
  33. core.Dispose();
  34. core = default!;
  35. GC.Collect();
  36. }
  37. [Benchmark(Description = "MoonSharp (RunString)")]
  38. public DynValue Benchmark_MoonSharp_String()
  39. {
  40. return core.MoonSharpState.DoString(core.SourceText);
  41. }
  42. [Benchmark(Description = "MoonSharp (RunFile)")]
  43. public DynValue Benchmark_MoonSharp_File()
  44. {
  45. return core.MoonSharpState.DoFile(core.FilePath);
  46. }
  47. [Benchmark(Description = "NLua (DoString)")]
  48. public object[] Benchmark_NLua_String()
  49. {
  50. return core.NLuaState.DoString(core.SourceText);
  51. }
  52. [Benchmark(Description = "NLua (DoFile)")]
  53. public object[] Benchmark_NLua_File()
  54. {
  55. return core.NLuaState.DoFile(core.FilePath);
  56. }
  57. [Benchmark(Description = "Lua-CSharp (DoString)")]
  58. public async Task<LuaValue> Benchmark_LuaCSharp_String()
  59. {
  60. await core.LuaCSharpState.DoStringAsync(core.SourceText, buffer);
  61. return buffer[0];
  62. }
  63. [Benchmark(Description = "Lua-CSharp (DoFileAsync)")]
  64. public async Task<LuaValue> Benchmark_LuaCSharp_File()
  65. {
  66. await core.LuaCSharpState.DoFileAsync(core.FilePath, buffer);
  67. return buffer[0];
  68. }
  69. }