AuroraRuntime/Source/HWInfo/AuCpuLoadSampler.cpp

123 lines
3.3 KiB
C++

/***
Copyright (C) 2023 J Reece Wilson (a/k/a "Reece"). All rights reserved.
File: CpuLoadSampler.cpp
Date: 2023-10-28
Author: Reece
***/
#include <Source/RuntimeInternal.hpp>
#include "AuCpuLoadSampler.hpp"
namespace Aurora::HWInfo
{
CpuLoadSamplerImpl::CpuLoadSamplerImpl(AuUInt32 uMinSamplePeriodMS,
bool bThreadMode) :
uMinSamplePeriod(uMinSamplePeriodMS),
bThreadMode(bThreadMode)
{
}
CpuLoadSamplerImpl::~CpuLoadSamplerImpl()
{
}
double CpuLoadSamplerImpl::GetLoad()
{
if (!this->bThreadMode)
{
return this->processState.GetLoad(this->uMinSamplePeriod, false);
}
else
{
return this->threadState->GetLoad(this->uMinSamplePeriod, true);
}
}
double CpuLoadSamplerState::GetLoad(AuUInt32 uMinSamplePeriod, bool bThread)
{
AuUInt64 now[2] = {
AuTime::SteadyClockNS(),
bThread ? AuTime::ThreadClockNS() : AuTime::ProcessClockNS()
};
double dDeltaSteady = now[0] - this->uPrevTimes[0];
double dDeltaProcess = now[1] - this->uPrevTimes[1];
double dUsage = 0;
double dMinSamplePeriod = double(AuMSToNS<AuUInt64>(uMinSamplePeriod));
if (!uMinSamplePeriod ||
dDeltaSteady >= dMinSamplePeriod)
{
dUsage = dDeltaProcess / dDeltaSteady;
this->uPrevTimes[1] = now[1];
this->uPrevTimes[0] = now[0];
this->dPrevLoad = dUsage;
}
else
{
dUsage = dDeltaProcess / dDeltaSteady;
#if 0
dUsage *= dDeltaSteady / double(dMinSamplePeriod);
if (this->dPrevLoad) dUsage = dUsage + this->dPrevLoad / 2.0;
#else
if (this->dPrevLoad)
{
double dFrameDelta = dDeltaSteady / double(dMinSamplePeriod);
double dFrameDeltaInverse = 1.0 - dFrameDelta;
dUsage *= dFrameDelta;
dUsage += this->dPrevLoad * dFrameDeltaInverse;
}
else
{
dUsage *= dDeltaSteady / double(dMinSamplePeriod);
}
#endif
}
if (!bool(this->uPrevTimes[0]))
{
this->uPrevTimes[1] = now[1];
this->uPrevTimes[0] = now[0];
return 0;
}
else
{
dUsage = dUsage * 100.0;
if (dUsage > 100.0)
{
return 100.0;
}
else if (dUsage < 0.0)
{
return 0.0;
}
else
{
return dUsage;
}
}
}
AUKN_SYM double GetProcessCPUUtilization()
{
static CpuLoadSamplerImpl gSampler(AuSToMS<AuUInt32>(1), false);
return gSampler.GetLoad();
}
AUKN_SYM ICpuLoadSampler *CpuLoadSamplerNew(AuUInt32 uMinSamplePeriodMS,
bool bThreadMode)
{
return _new CpuLoadSamplerImpl(uMinSamplePeriodMS, bThreadMode);
}
AUKN_SYM void CpuLoadSamplerRelease(ICpuLoadSampler *pEvent)
{
AuSafeDelete<CpuLoadSamplerImpl *>(pEvent);
}
AUROXTL_INTERFACE_SOO_SRC_EX(AURORA_SYMBOL_EXPORT, CpuLoadSampler, CpuLoadSamplerImpl, (AuUInt32, uMinSamplePeriod), (bool, bThreadMode))
}