// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using System.Diagnostics; using System.Runtime.CompilerServices; using Xunit.Abstractions; namespace SixLabors.ImageSharp.Tests { /// /// Utility class to measure the execution of an operation. It can be used either by inheritance or by composition. /// public class MeasureFixture { /// /// Value indicating whether priniting is enabled. /// protected bool EnablePrinting = true; /// /// Measures and prints the execution time of an , executed multiple times. /// /// A value indicating how many times to run the action /// The to execute /// The name of the operation to print to the output public void Measure(int times, Action action, [CallerMemberName] string operationName = null) { if (this.EnablePrinting) { this.Output?.WriteLine($"{operationName} X {times} ..."); } var sw = Stopwatch.StartNew(); for (int i = 0; i < times; i++) { action(); } sw.Stop(); if (this.EnablePrinting) { this.Output?.WriteLine($"{operationName} finished in {sw.ElapsedMilliseconds} ms"); } } /// /// Initializes a new instance of /// /// A instance to print the results public MeasureFixture(ITestOutputHelper output) { this.Output = output; } protected ITestOutputHelper Output { get; } } public class MeasureGuard : IDisposable { private readonly string operation; private readonly Stopwatch stopwatch = new Stopwatch(); public MeasureGuard(ITestOutputHelper output, string operation) { this.operation = operation; this.Output = output; this.Output.WriteLine(operation + " ..."); this.stopwatch.Start(); } private ITestOutputHelper Output { get; } public void Dispose() { this.stopwatch.Stop(); this.Output.WriteLine($"{this.operation} completed in {this.stopwatch.ElapsedMilliseconds}ms"); } } }