using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime; using System.Runtime.InteropServices; using System.Text.Json; using BonniePDF; using Microsoft.Win32; const int coldLaunches = 10; const int warmLaunches = 3; const string sourceRevision = "0f9693b25a3cbf7b6fcf99522aa52e9b2052f6e2"; CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; var workloads = new[] { new Workload("invoice", BuildInvoice, 1_000, 100), new Workload("chart-report", BuildChartReport, 1_000, 100), new Workload("long-document", BuildLongDocument, 10, 5), }; var json = new JsonSerializerOptions(JsonSerializerDefaults.Web) { WriteIndented = true }; if (args is ["sample", var sampleId, var samplePath]) { BonniePdfLicense.Tier = LicenseTier.Evaluation; File.WriteAllBytes(samplePath, Generate(workloads.Single(workload => workload.Id == sampleId))); return 0; } if (args is ["worker", var id, var phase]) { var workload = workloads.Single(workload => workload.Id == id); BonniePdfLicense.Tier = LicenseTier.Evaluation; using var process = Process.GetCurrentProcess(); int warmup = phase == "warm" ? workload.Warmup : 0; int samples = phase == "warm" ? workload.Samples : 1; for (int i = 0; i < warmup; i++) Generate(workload); var milliseconds = new double[samples]; var bytes = new int[samples]; for (int i = 0; i < samples; i++) { long start = Stopwatch.GetTimestamp(); var pdf = Generate(workload); milliseconds[i] = Stopwatch.GetElapsedTime(start).TotalMilliseconds; bytes[i] = pdf.Length; } process.Refresh(); Console.WriteLine(JsonSerializer.Serialize(new Launch(milliseconds, bytes, process.PeakWorkingSet64), json)); return 0; } if (args.Length != 1 || args[0].StartsWith("--", StringComparison.Ordinal)) { Console.Error.WriteLine("Usage: dotnet Benchmarks.dll "); return 1; } var assembly = typeof(Document).Assembly; string version = assembly.GetCustomAttribute()!.InformationalVersion; if (!version.EndsWith("+" + sourceRevision, StringComparison.Ordinal)) throw new InvalidOperationException($"Build the benchmark against BonniePDF source revision {sourceRevision}. Found {version}."); if (assembly.GetCustomAttribute()?.IsJITOptimizerDisabled == true || Assembly.GetExecutingAssembly().GetCustomAttribute()?.IsJITOptimizerDisabled == true) throw new InvalidOperationException("Build both projects in Release."); var runs = workloads.Select(workload => new WorkloadRun(workload)).ToArray(); var startedUtc = DateTimeOffset.UtcNow; RunRoundRobin(coldLaunches, "cold", run => run.Cold); RunRoundRobin(warmLaunches, "warm", run => run.Warm); BonniePdfLicense.Tier = LicenseTier.Evaluation; foreach (var run in runs) run.Pages = InspectPdf(Generate(run.Workload)); string? processor = OperatingSystem.IsWindows() ? Registry.GetValue(@"HKEY_LOCAL_MACHINE\HARDWARE\DESCRIPTION\System\CentralProcessor\0", "ProcessorNameString", null) as string : null; var results = new { startedUtc, completedUtc = DateTimeOffset.UtcNow, version, sourceRevision, configuration = "Release", runtime = RuntimeInformation.FrameworkDescription, os = RuntimeInformation.OSDescription, architecture = RuntimeInformation.ProcessArchitecture.ToString(), processor = processor?.Trim(), logicalProcessors = Environment.ProcessorCount, gc = GCSettings.IsServerGC ? "Server" : "Workstation", coldLaunches, warmLaunches, workloads = runs.Select(run => new { run.Workload.Id, run.Workload.Warmup, samplesPerWarmLaunch = run.Workload.Samples, run.Pages, run.Cold, run.Warm, }), }; File.WriteAllText(args[0], JsonSerializer.Serialize(results, json) + Environment.NewLine); return 0; void RunRoundRobin(int rounds, string phase, Func> destination) { for (int round = 0; round < rounds; round++) { for (int i = 0; i < runs.Length; i++) { var run = runs[(i + round) % runs.Length]; Console.Error.WriteLine($"{phase} {round + 1}/{rounds} {run.Workload.Id}"); var start = Command(Environment.ProcessPath!); if (Path.GetFileNameWithoutExtension(start.FileName).Equals("dotnet", StringComparison.OrdinalIgnoreCase)) start.ArgumentList.Add(Assembly.GetExecutingAssembly().Location); foreach (string argument in new[] { "worker", run.Workload.Id, phase }) start.ArgumentList.Add(argument); using var process = Process.Start(start)!; var output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) throw new InvalidOperationException($"Benchmark worker failed with exit code {process.ExitCode}."); destination(run).Add(JsonSerializer.Deserialize(output, json)!); } } } static byte[] Generate(Workload workload) => workload.Build().GenerateBytes(); static int InspectPdf(byte[] bytes) { string file = Path.GetTempFileName(); try { File.WriteAllBytes(file, bytes); var start = Command("pdfinfo"); start.ArgumentList.Add(file); start.Environment["LC_ALL"] = "C"; using var process = Process.Start(start)!; string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); if (process.ExitCode != 0) throw new InvalidDataException("Poppler could not inspect the generated PDF."); string[] lines = output.Split('\n'); var pages = lines.Single(line => line.StartsWith("Pages:", StringComparison.Ordinal)); var tagged = lines.Single(line => line.StartsWith("Tagged:", StringComparison.Ordinal)); if (tagged.Split(':')[1].Trim() != "no") throw new InvalidDataException("The benchmark expects untagged PDF output."); return int.Parse(pages.Split(':')[1].Trim(), CultureInfo.InvariantCulture); } finally { File.Delete(file); } } static ProcessStartInfo Command(string program) => new(program) { UseShellExecute = false, RedirectStandardOutput = true, }; static Document NewDocument(string title) => new(new DocumentSettings { PageSize = PdfSize.A4, Margin = 36, Version = PdfVersion.Pdf17, Accessibility = AccessibilityMode.None, Conformance = PdfAConformance.None, Language = "en-GB", DefaultTextStyle = new TextStyle().WithFamily("Helvetica").WithSize(10), }) { Metadata = new DocumentMetadata { Title = title }, }; static Document BuildInvoice() { var doc = NewDocument("Northstar Workshop invoice"); doc.Add(new Heading("Northstar Workshop invoice") { Level = 1, FontSize = 22 }); doc.Add(new TextBlock("Invoice NW-1042 | Issued 12 October 2026 | Payable 11 November 2026")); doc.Add(new TextBlock("Bill to Alder Studio, 32 Sample Road, Bristol")); var table = new Table(4); table.AddHeader("Description", "Quantity", "Unit price", "Amount"); string[] items = [ "Oak sample panel", "Brass mounting plate", "Birch tray", "Linen sleeve", "Display stand", "Cutting service", "Surface finish", "Drawer insert", "Felt backing", "Edge banding", "Assembly", "Packaging", ]; decimal total = 0; for (int i = 0; i < items.Length; i++) { int quantity = i % 4 + 1; decimal price = 9.50m + i * 2.25m; total += quantity * price; table.AddRow(items[i], $"{quantity}", $"£{price:N2}", $"£{quantity * price:N2}"); } doc.Add(table); doc.Add(new TextBlock($"Total payable £{total:N2}")); return doc; } static Document BuildChartReport() { var doc = NewDocument("Northstar Workshop operating report"); doc.Add(new Heading("Northstar Workshop operating report") { Level = 1, FontSize = 22 }); doc.Add(new TextBlock("Illustrative revenue and order figures for 2025.")); var monthly = new[] { 44, 51, 49, 56, 61, 64, 62, 73, 68, 78, 84, 89 }; var months = new[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; doc.Add(new BarChart { Height = 186, StretchToFit = true, Data = new ChartData { YAxis = new AxisOptions { MaxValue = 100, StepCount = 5 }, Series = [new ChartSeries { Name = "Revenue (£ thousands)", Color = Color.FromHex("#2359a2"), DataPoints = months.Select((label, index) => new ChartDataPoint { Label = label, Value = monthly[index] }).ToList(), }], }, }); doc.Add(new PieChart { Height = 182, StretchToFit = true, IsDonut = true, Data = new ChartData { Series = [new ChartSeries { DataPoints = [ new ChartDataPoint { Label = "Workshop", Value = 360 }, new ChartDataPoint { Label = "Design", Value = 240 }, new ChartDataPoint { Label = "Delivery", Value = 179 }, ], }], }, }); var table = new Table(3); table.AddHeader("Quarter", "Revenue (£ thousands)", "Orders"); for (int quarter = 0; quarter < 4; quarter++) table.AddRow($"Q{quarter + 1}", $"{monthly.Skip(quarter * 3).Take(3).Sum()}", $"{72 + quarter * 15}"); doc.Add(table); return doc; } static Document BuildLongDocument() { var doc = NewDocument("Northstar Workshop inspection log"); doc.Add(new Heading("Northstar Workshop inspection log") { Level = 1, FontSize = 18 }); for (int i = 1; i <= 100_000; i++) doc.Add(new TextBlock($"Inspection {i:D6} | Station {i % 24 + 1:D2} | Sample {i % 128:D3} accepted.")); return doc; } sealed record Workload(string Id, Func Build, int Warmup, int Samples); sealed record Launch(double[] Milliseconds, int[] PdfBytes, long PeakWorkingSetBytes); sealed record WorkloadRun(Workload Workload) { public List Cold { get; } = []; public List Warm { get; } = []; public int Pages { get; set; } }