// Copyright (c) Six Labors.
// Licensed under the Six Labors Split License.
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 printing 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} ...");
}
Stopwatch 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();
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");
}
}