AyCode.Core/BenchmarkSuite1/TaskHelperBenchmarks.cs

66 lines
2.5 KiB
C#

using AyCode.Core.Helpers;
using BenchmarkDotNet.Attributes;
using Microsoft.VSDiagnostics;
namespace AyCode.Core.Benchmarks;
[CPUUsageDiagnoser]
public class TaskHelperBenchmarks
{
private volatile bool _flag;
private int _counter;
private Action _incrementAction = null !;
private Func<int> _incrementFunc = null !;
private Func<Task<int>> _incrementAsyncFunc = null !;
[GlobalSetup]
public void Setup()
{
_incrementAction = () => _counter++;
_incrementFunc = () => ++_counter;
_incrementAsyncFunc = async () =>
{
await Task.Yield();
return ++_counter;
};
}
[IterationSetup]
public void IterationSetup()
{
_flag = true; // Pre-set for immediate success
_counter = 0;
}
#region WaitToAsync Benchmarks
[Benchmark(Description = "WaitToAsync - immediate success")]
[BenchmarkCategory("WaitToAsync")]
public Task<bool> WaitToAsync_ImmediateSuccess() => TaskHelper.WaitToAsync(() => _flag, 1000, 1);
[Benchmark(Description = "WaitToAsync - short timeout (100ms)")]
[BenchmarkCategory("WaitToAsync")]
public Task<bool> WaitToAsync_ShortTimeout() => TaskHelper.WaitToAsync(() => true, 100, 1);
#endregion
#region ToThreadPoolTask Benchmarks
[Benchmark(Description = "ToThreadPoolTask - Action")]
[BenchmarkCategory("ThreadPool")]
public Task ToThreadPoolTask_Action() => _incrementAction.ToThreadPoolTask();
[Benchmark(Description = "ToThreadPoolTask - Func<T>")]
[BenchmarkCategory("ThreadPool")]
public Task<int> ToThreadPoolTask_FuncT() => _incrementFunc.ToThreadPoolTask();
[Benchmark(Description = "ToThreadPoolTask - Func<Task<T>>")]
[BenchmarkCategory("ThreadPool")]
public Task<int> ToThreadPoolTask_FuncTaskT() => _incrementAsyncFunc.ToThreadPoolTask();
[Benchmark(Description = "Task.Run baseline - Action")]
[BenchmarkCategory("ThreadPool")]
public Task TaskRun_Action_Baseline() => Task.Run(_incrementAction);
#endregion
#region Timing Method Comparison
[Benchmark(Description = "DateTime.UtcNow.Ticks")]
[BenchmarkCategory("Timing")]
public long DateTimeUtcNow_Ticks() => DateTime.UtcNow.Ticks;
[Benchmark(Description = "Environment.TickCount64")]
[BenchmarkCategory("Timing")]
public long EnvironmentTickCount64() => Environment.TickCount64;
[Benchmark(Description = "DateTime.UtcNow.AddMilliseconds")]
[BenchmarkCategory("Timing")]
public long DateTimeUtcNow_AddMilliseconds() => DateTime.UtcNow.AddMilliseconds(1000).Ticks;
#endregion
}