using System;
using System.Diagnostics;
namespace TestsForUnitTestSharp
{
///
/// Spins the calling thread until it has used a given amount of CPU, however contended the machine is.
///
public static class CpuBurner
{
///
/// Bounds a burn that can't reach its target, so a broken clock fails its test instead of hanging it.
///
public static readonly TimeSpan WallClockCap = TimeSpan.FromSeconds(5);
public static void Burn(TimeSpan cpu)
{
// Measured on the process rather than the thread, so the burn doesn't lean on the ThreadCpuClock that
// several callers are testing. Tests run one at a time, so this thread is nearly all the process uses.
Process process = Process.GetCurrentProcess();
TimeSpan target = process.TotalProcessorTime + cpu;
var elapsed = Stopwatch.StartNew();
double accumulator = 0;
while (elapsed.Elapsed < WallClockCap)
{
for (int i = 0; i < 10000; ++i)
{
accumulator += Math.Sqrt(accumulator + 1);
}
if (process.TotalProcessorTime >= target)
{
return;
}
}
}
}
}