|
| 1 | +namespace FSharp.TypeProviders.SDK.Benchmarks |
| 2 | + |
| 3 | +open System |
| 4 | +open System.Collections.Generic |
| 5 | +open System.Reflection |
| 6 | +open BenchmarkDotNet.Attributes |
| 7 | +open Microsoft.FSharp.Core.CompilerServices |
| 8 | +open Microsoft.FSharp.Quotations |
| 9 | +open ProviderImplementation.ProvidedTypes |
| 10 | + |
| 11 | +// --------------------------------------------------------------------------- |
| 12 | +// Shared helpers (module required because namespaces cannot contain let-bindings) |
| 13 | +// --------------------------------------------------------------------------- |
| 14 | + |
| 15 | +[<AutoOpen>] |
| 16 | +module internal BenchmarkHelpers = |
| 17 | + |
| 18 | + // Minimal simulation of the F# compiler host required by the SDK's |
| 19 | + // cross-targeting assembly resolver (mirrors ProvidedTypesTesting.fs). |
| 20 | + |
| 21 | + [<AllowNullLiteral>] |
| 22 | + type private DllInfo(path: string) = |
| 23 | + member _.FileName = path |
| 24 | + |
| 25 | + // The type must be named TcImports and expose Base + DllInfos. |
| 26 | + type private TcImports(bas: TcImports option, dllInfosInitial: DllInfo list) = |
| 27 | + let mutable dllInfos = dllInfosInitial |
| 28 | + member _.Base = bas |
| 29 | + member _.DllInfos = dllInfos |
| 30 | + |
| 31 | + let private setProp (cfg: TypeProviderConfig) (prop: string) (value: obj) = |
| 32 | + let ty = cfg.GetType() |
| 33 | + match ty.GetProperty(prop, BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic) with |
| 34 | + | null -> |
| 35 | + let fld = ty.GetField(prop, BindingFlags.Instance ||| BindingFlags.Public ||| BindingFlags.NonPublic) |
| 36 | + if isNull fld then failwith ("expected TypeProviderConfig to have a property or field " + prop) |
| 37 | + fld.SetValue(cfg, value) |
| 38 | + | p -> p.GetSetMethod(nonPublic = true).Invoke(cfg, [| value |]) |> ignore |
| 39 | + |
| 40 | + /// Build the list of referenced assemblies from the currently-loaded AppDomain. |
| 41 | + let buildRefs () = |
| 42 | + let asms = |
| 43 | + AppDomain.CurrentDomain.GetAssemblies() |
| 44 | + |> Array.filter (fun x -> not x.IsDynamic && x.Location <> "") |
| 45 | + |> Array.map (fun x -> x.Location) |
| 46 | + let runtimeAssembly = |
| 47 | + asms |
| 48 | + |> Array.find (fun x -> |
| 49 | + match IO.Path.GetFileNameWithoutExtension(x).ToLower() with |
| 50 | + | "mscorlib" | "system.runtime" -> true |
| 51 | + | _ -> false) |
| 52 | + runtimeAssembly, Array.toList asms |
| 53 | + |
| 54 | + /// Create a TypeProviderConfig that properly simulates the F# compiler host. |
| 55 | + let makeConfig () = |
| 56 | + let runtimeAssembly, runtimeAssemblyRefs = buildRefs () |
| 57 | + let cfg = TypeProviderConfig(fun _ -> false) |
| 58 | + cfg.IsHostedExecution <- false |
| 59 | + cfg.IsInvalidationSupported <- true |
| 60 | + cfg.ResolutionFolder <- __SOURCE_DIRECTORY__ |
| 61 | + cfg.RuntimeAssembly <- runtimeAssembly |
| 62 | + cfg.ReferencedAssemblies <- Array.ofList runtimeAssemblyRefs |
| 63 | + |
| 64 | + // Set up the systemRuntimeContainsType closure with the shape expected by |
| 65 | + // AssemblyResolver.fs (must close over a value named `tcImports`). |
| 66 | + let dllInfos = [ yield DllInfo(runtimeAssembly); for r in runtimeAssemblyRefs do yield DllInfo(r) ] |
| 67 | + let tcImports = TcImports(Some(TcImports(None, [])), dllInfos) |
| 68 | + let systemRuntimeContainsType = (fun (_s: string) -> if tcImports.DllInfos.Length = 1 then true else true) |
| 69 | + setProp cfg "systemRuntimeContainsType" systemRuntimeContainsType |
| 70 | + cfg |
| 71 | + |
| 72 | + // --------------------------------------------------------------------------- |
| 73 | + // Stress scenario: many methods with repeated common types |
| 74 | + // --------------------------------------------------------------------------- |
| 75 | + |
| 76 | + /// Build a generative assembly with `typeCount` types, each having `methodsPerType` |
| 77 | + /// static methods whose parameters and return types are drawn from a small set of |
| 78 | + /// commonly-used .NET types. This maximises cache hits for `transType`. |
| 79 | + let buildLargeGenerativeAssembly (typeCount: int) (methodsPerType: int) = |
| 80 | + let cfg = makeConfig () |
| 81 | + let tp = new TypeProviderForNamespaces(cfg) |
| 82 | + |
| 83 | + let ns = "BenchmarkNamespace" |
| 84 | + let tempAssembly = ProvidedAssembly() |
| 85 | + |
| 86 | + // The common types that appear repeatedly in real-world schemas. |
| 87 | + let commonTypes = |
| 88 | + [| typeof<string>; typeof<int>; typeof<bool>; typeof<float>; typeof<int64> |
| 89 | + typeof<DateTime>; typeof<Guid>; typeof<decimal>; typeof<byte[]> |
| 90 | + typeof<string option>; typeof<int option>; typeof<bool option> |] |
| 91 | + |
| 92 | + for i in 0 .. typeCount - 1 do |
| 93 | + let container = |
| 94 | + ProvidedTypeDefinition( |
| 95 | + tempAssembly, ns, |
| 96 | + sprintf "GeneratedType%d" i, |
| 97 | + Some typeof<obj>, isErased = false) |
| 98 | + |
| 99 | + for m in 0 .. methodsPerType - 1 do |
| 100 | + // Cycle through common types for parameters and return types so that |
| 101 | + // transType is called many times with the same Type objects. |
| 102 | + let retTy = commonTypes.[m % commonTypes.Length] |
| 103 | + let param1Ty = commonTypes.[(m + 1) % commonTypes.Length] |
| 104 | + let param2Ty = commonTypes.[(m + 2) % commonTypes.Length] |
| 105 | + let meth = |
| 106 | + ProvidedMethod( |
| 107 | + sprintf "Method%d" m, |
| 108 | + [ ProvidedParameter("a", param1Ty) |
| 109 | + ProvidedParameter("b", param2Ty) ], |
| 110 | + retTy, |
| 111 | + invokeCode = (fun _ -> Expr.Value(null, retTy)), |
| 112 | + isStatic = true) |
| 113 | + container.AddMember meth |
| 114 | + |
| 115 | + tempAssembly.AddTypes [container] |
| 116 | + tp.AddNamespace(ns, [container]) |
| 117 | + |
| 118 | + // Return the tp and the first type so the caller can trigger compilation. |
| 119 | + let providedType = |
| 120 | + tp.Namespaces.[0].GetTypes().[0] :?> ProvidedTypeDefinition |
| 121 | + tp, providedType |
| 122 | + |
| 123 | +// --------------------------------------------------------------------------- |
| 124 | +// Benchmark classes |
| 125 | +// --------------------------------------------------------------------------- |
| 126 | + |
| 127 | +/// Benchmarks the compilation of a large generative type provider. |
| 128 | +/// Setup (creating ProvidedTypeDefinitions) happens in [IterationSetup]; only |
| 129 | +/// GetGeneratedAssemblyContents (which calls transType internally) is timed. |
| 130 | +[<MemoryDiagnoser>] |
| 131 | +[<SimpleJob(launchCount = 1, warmupCount = 3, iterationCount = 10)>] |
| 132 | +type GenerativeCompilationBenchmark() = |
| 133 | + |
| 134 | + // Pre-built providers ready for compilation in each iteration. |
| 135 | + // We keep a queue because GetGeneratedAssemblyContents consumes the assembly. |
| 136 | + let mutable pool: (TypeProviderForNamespaces * ProvidedTypeDefinition) Queue = Queue() |
| 137 | + |
| 138 | + [<Params(50, 200)>] |
| 139 | + member val TypeCount = 50 with get, set |
| 140 | + |
| 141 | + [<Params(20)>] |
| 142 | + member val MethodsPerType = 20 with get, set |
| 143 | + |
| 144 | + /// Fill the pool before each iteration starts. |
| 145 | + [<IterationSetup>] |
| 146 | + member this.Setup() = |
| 147 | + // Ensure at least 2 providers are ready (warmup + iteration). |
| 148 | + while pool.Count < 2 do |
| 149 | + pool.Enqueue(buildLargeGenerativeAssembly this.TypeCount this.MethodsPerType) |
| 150 | + |
| 151 | + [<Benchmark(Description = "CompileGenerativeAssembly")>] |
| 152 | + member _.CompileGenerativeAssembly() = |
| 153 | + let tp, providedType = pool.Dequeue() |
| 154 | + let bytes = (tp :> ITypeProvider).GetGeneratedAssemblyContents(providedType.Assembly) |
| 155 | + (tp :> IDisposable).Dispose() |
| 156 | + bytes.Length // return value to prevent dead-code elimination |
| 157 | + |
| 158 | + |
| 159 | +/// Stress scenario: simulate a large schema provider (like SwaggerProvider over |
| 160 | +/// a big OpenAPI spec) by generating 500 types with 10 methods each, all using |
| 161 | +/// the same handful of primitive types. This is the scenario most improved by |
| 162 | +/// the transType memoization fix. |
| 163 | +[<MemoryDiagnoser>] |
| 164 | +[<SimpleJob(launchCount = 1, warmupCount = 2, iterationCount = 5)>] |
| 165 | +type LargeSchemaProviderBenchmark() = |
| 166 | + |
| 167 | + let mutable pool: (TypeProviderForNamespaces * ProvidedTypeDefinition) Queue = Queue() |
| 168 | + |
| 169 | + [<IterationSetup>] |
| 170 | + member _.Setup() = |
| 171 | + while pool.Count < 2 do |
| 172 | + pool.Enqueue(buildLargeGenerativeAssembly 500 10) |
| 173 | + |
| 174 | + [<Benchmark(Description = "CompileLargeSchema_500types_10methods")>] |
| 175 | + member _.CompileLargeSchema() = |
| 176 | + let tp, providedType = pool.Dequeue() |
| 177 | + let bytes = (tp :> ITypeProvider).GetGeneratedAssemblyContents(providedType.Assembly) |
| 178 | + (tp :> IDisposable).Dispose() |
| 179 | + bytes.Length |
| 180 | + |
0 commit comments