MegaBites-AI/Windows-powershell
0372
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4#if NET6_05 6using System;7using System.Collections.Generic;8using System.IO;9using System.Management.Automation;10using System.Management.Automation.Language;11 12using BenchmarkDotNet.Attributes;13using MicroBenchmarks;14 15namespace Engine16{17 [BenchmarkCategory(Categories.Engine, Categories.Internal)]18 public class Compiler19 {20 private static readonly Dictionary<string, ScriptBlockAst> s_scriptBlocksDict;21 private static readonly List<string> s_functionNames;22 private ScriptBlockAst _currentAst;23 24 static Compiler()25 {26 string pattern = string.Format("{0}test{0}perf{0}benchmarks", Path.DirectorySeparatorChar);27 string location = typeof(Compiler).Assembly.Location;28 string testFilePath = null;29 30 int start = location.IndexOf(pattern, StringComparison.Ordinal);31 if (start > 0)32 {33 testFilePath = Path.Join(location.AsSpan(0, start + pattern.Length), "assets", "compiler.test.ps1");34 }35 36 var topScriptBlockAst = Parser.ParseFile(testFilePath, tokens: out _, errors: out _);37 var allFunctions = topScriptBlockAst.FindAll(ast => ast is FunctionDefinitionAst, searchNestedScriptBlocks: false);38 39 s_scriptBlocksDict = new Dictionary<string, ScriptBlockAst>(capacity: 16);40 s_functionNames = new List<string>(capacity: 16);41 42 foreach (FunctionDefinitionAst function in allFunctions)43 {44 s_functionNames.Add(function.Name);45 s_scriptBlocksDict.Add(function.Name, function.Body);46 }47 }48 49 [ParamsSource(nameof(FunctionName))]50 public string FunctionsToCompile { get; set; }51 52 public IEnumerable<string> FunctionName() => s_functionNames;53 54 [GlobalSetup(Target = nameof(CompileFunction))]55 public void GlobalSetup()56 {57 _currentAst = s_scriptBlocksDict[FunctionsToCompile];58 59 // Run it once to get the C# code jitted.60 // The first call to this takes relatively too long, which makes the BDN's heuristic incorrectly61 // believe that there is no need to run many ops in each iteration. However, the subsequent runs62 // of this method is much faster than the first run, and this causes 'MinIterationTime' warnings63 // to our benchmarks and make the benchmark results not reliable.64 // Calling this method once in 'GlobalSetup' is a workaround.65 // See https://github.com/dotnet/BenchmarkDotNet/issues/837#issuecomment-82860015766 CompileFunction();67 }68 69 [Benchmark]70 public bool CompileFunction()71 {72 var compiledData = new CompiledScriptBlockData(_currentAst, isFilter: false);73 return compiledData.Compile(true);74 }75 }76}77 78#endif79 