2019-12-22 11:50:47 +00:00
|
|
|
using System.Diagnostics;
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
using Serilog;
|
|
|
|
|
|
|
|
namespace PluralKit.Bot
|
|
|
|
{
|
|
|
|
public class CpuStatService
|
|
|
|
{
|
2020-08-29 11:46:27 +00:00
|
|
|
private readonly ILogger _logger;
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-12-22 11:50:47 +00:00
|
|
|
public double LastCpuMeasure { get; private set; }
|
|
|
|
|
|
|
|
public CpuStatService(ILogger logger)
|
|
|
|
{
|
|
|
|
_logger = logger;
|
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Gets the current CPU usage. Estimation takes ~5 seconds (of mostly sleeping).
|
|
|
|
/// </summary>
|
|
|
|
public async Task<double> EstimateCpuUsage()
|
|
|
|
{
|
|
|
|
// We get the current processor time, wait 5 seconds, then compare
|
|
|
|
// https://medium.com/@jackwild/getting-cpu-usage-in-net-core-7ef825831b8b
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2020-05-05 16:12:45 +00:00
|
|
|
_logger.Debug("Estimating CPU usage...");
|
2019-12-22 11:50:47 +00:00
|
|
|
var stopwatch = new Stopwatch();
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-12-22 11:50:47 +00:00
|
|
|
stopwatch.Start();
|
|
|
|
var cpuTimeBefore = Process.GetCurrentProcess().TotalProcessorTime;
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-12-22 11:50:47 +00:00
|
|
|
await Task.Delay(5000);
|
2021-08-27 15:03:47 +00:00
|
|
|
|
2019-12-22 11:50:47 +00:00
|
|
|
stopwatch.Stop();
|
|
|
|
var cpuTimeAfter = Process.GetCurrentProcess().TotalProcessorTime;
|
|
|
|
|
|
|
|
var cpuTimePassed = cpuTimeAfter - cpuTimeBefore;
|
|
|
|
var timePassed = stopwatch.Elapsed;
|
|
|
|
|
|
|
|
var percent = cpuTimePassed / timePassed;
|
2020-05-05 16:12:45 +00:00
|
|
|
_logger.Debug("CPU usage measured as {Percent:P}", percent);
|
2019-12-22 11:50:47 +00:00
|
|
|
LastCpuMeasure = percent;
|
|
|
|
return percent;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|