Monitoring CPU usage

通过一个简单的控制组件,您可以监控移动设备的CPU使用情况。该组件包括两个定时器:一个用于周期性调用绘图函数,另一个(低优先级空闲)用于计算空闲时间。这样,您就可以大致了解其他线程的CPU使用情况。

Monitoring CPU usage

From Forum Nokia Wiki

This simple control allows you to monitor CPU usage in your mobile. To use it, just instantiate the control and set two timers: one is used to periodically invoke the plot function, and the other one (low priority idle) to count the idle time. This way, you can get an approximation on how much cpu other threads are using.

void CSystemView::ConstructL()
{
iUpdateTimer = CPeriodic::NewL(CActive::EPriorityHigh);
iIdleTimer = CPeriodic::NewL(CActive::EPriorityIdle);
}
 
void CSystemView::CmdStartTimers()
{
// Reset counters
iIdleCounter = 0;
iCPUControl->Reset();
DrawDeferred();
 
const TInt KUpdateInterval = 1000000; // 1 sec
iUpdateTimer->Start(KUpdateInterval, KUpdateInterval, TCallBack(DoUpdateL, this));
 
const TInt KIdleInterval = 10000; // 0.01 sec
iIdleTimer->Start(KIdleInterval, KIdleInterval, TCallBack(DoIdleL, this));
}
 
TInt CSystemView::DoUpdateL(TAny* aPtr)
{
CSystemView* self = static_cast<CSystemView*>(aPtr);
 
TInt idle = self->iIdleCounter;
self->iIdleCounter = 0;
 
self->iCPUControl->PlotL(idle);
 
return 0;
}
 
TInt CSystemView::DoIdleL(TAny* aPtr)
{
CSystemView* self = static_cast<CSystemView*>(aPtr);
++self->iIdleCounter;
 
return 0;
}
#include <coecntrl.h>   // CCoeControl
 
class CCPUControl : public CCoeControl
{
public:
void ConstructL(const TRect& aRect, const CCoeControl* aParent);
~CCPUControl();
 
void Reset();
void PlotL(TInt aIdleCounter);
 
private:
void Draw(const TRect& aRect) const;
void SizeChanged();
 
private:
CArrayFix<TReal32>* iCpuLoadList;
TInt iMaxIdleCounter;
TReal32 iCpuLoad;
TReal32 iTotalCpuLoad;
TUint32 iTotalTicks;
 
CArrayFix<TPoint>* iPointList;
TRect iPaintRect;
 
HBufC* iCPULoadText;
};
#include "CPUControl.h"
#include <YourApp.rsg>
 
#include <coemain.h> // CCoeEnv
#include <eikenv.h> // CEikonEnv
 
// Handle any possible FPU exception
void FpHandler(TExcType /*aType*/)
{}
 
void CCPUControl::ConstructL(const TRect& aRect, const CCoeControl* aParent)
{
if (aParent == 0)
CreateWindowL();
else
SetContainerWindowL(*aParent);
 
#if defined(__S603RD__)
User::SetExceptionHandler(FpHandler, KExceptionFpe);
#else
RThread().SetExceptionHandler(FpHandler, KExceptionFpe);
#endif
 
iCpuLoadList = new(ELeave) CArrayFixSeg<TReal32>(5);
iPointList = new(ELeave) CArrayFixFlat<TPoint>(5);
 
iCPULoadText = iCoeEnv->AllocReadResourceL(R_TEXT_CPU_LOAD);
 
SetRect(aRect);
ActivateL();
}
 
CCPUControl::~CCPUControl()
{
delete iCPULoadText;
 
delete iPointList;
delete iCpuLoadList;
}
 
void CCPUControl::Reset()
{
iCpuLoadList->Reset();
iCpuLoad = 0;
iTotalCpuLoad = 0;
iTotalTicks = 0;
iMaxIdleCounter = 0;
 
iPointList->Reset();
}
 
void CCPUControl::Draw(const TRect& /*aRect*/) const
{
CWindowGc& gc = SystemGc();
 
gc.Clear(iPaintRect);
gc.SetClippingRect(iPaintRect);
gc.SetPenColor(KRgbRed);
gc.DrawPolyLine(iPointList);
 
gc.SetPenColor(KRgbBlack);
gc.DrawRect(iPaintRect);
 
const CFont* font = iEikonEnv->LegendFont();
gc.UseFont(font);
 
TBuf<64> cpuLoadText;
cpuLoadText.Format(*iCPULoadText, static_cast<TInt>(iCpuLoad * 100),
iTotalTicks? (iTotalCpuLoad / iTotalTicks) * 100 : 0);
 
gc.DrawText(cpuLoadText, iPaintRect, font->HeightInPixels(), CGraphicsContext::ERight);
gc.DiscardFont();
}
 
void CCPUControl::SizeChanged()
{
iPaintRect = Rect();
iPaintRect.Shrink(5, 5);
}
 
void CCPUControl::PlotL(TInt aIdleCounter)
{
if (aIdleCounter > iMaxIdleCounter)
iMaxIdleCounter = aIdleCounter;
 
iCpuLoad = static_cast<TReal32> ((0.8 * (iMaxIdleCounter - aIdleCounter))
/ iMaxIdleCounter + 0.2 * iCpuLoad);
// To calculate average load
iTotalCpuLoad += iCpuLoad;
++iTotalTicks;
 
if (iCpuLoadList->Count() == iPaintRect.Width() - 2)
iCpuLoadList->Delete(0);
iCpuLoadList->AppendL(iCpuLoad);
 
iPointList->Reset();
for (TInt i = 0; i < iCpuLoadList->Count(); ++i)
{
TInt x = iPaintRect.iBr.iX - 1 - iCpuLoadList->Count() + i;
TInt y = iPaintRect.iBr.iY - 2 -
static_cast<TInt> (iPaintRect.Height() * iCpuLoadList->At(i));
iPointList->AppendL(TPoint(x, y));
}
 
DrawDeferred();
}

You can check TaskSpy source code to see how this works.

Console.WriteLine("Starting high CPU and memory load simulation..."); // 启动 CPU 负载模拟 Task cpuTask = Task.Run(() => SimulateHighCpuUsage()); // 启动内存负载模拟 SimulateHighMemoryUsage(); Console.WriteLine("Simulation completed."); 应用一下方法 实现 动态占用 CPU 内存 到80% using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; class Program { static void Main(string[] args) { Console.WriteLine("Monitoring CPU usage across platforms..."); while (true) { double cpuUsage = GetCpuUsage(); Console.WriteLine($"Current CPU Usage: {cpuUsage:F2}%"); Thread.Sleep(1000); } } static double GetCpuUsage() { if (OperatingSystem.IsWindows()) { return GetCpuUsageWindows(); } else if (OperatingSystem.IsLinux()) { return GetCpuUsageLinux(); } else if (OperatingSystem.IsMacOS()) { return GetCpuUsageMacOS(); } else { Console.WriteLine("Unsupported OS for CPU monitoring."); return 0; } } // Windows: 使用 PerformanceCounter static PerformanceCounter _cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total"); static double GetCpuUsageWindows() { _cpuCounter.NextValue(); // 第一次调用返回 0 Thread.Sleep(500); return _cpuCounter.NextValue(); } // Linux: 读取 /proc/stat static Dictionary<string, long[]> previousCpuTimes = new Dictionary<string, long[]>(); static double GetCpuUsageLinux() { string[] lines = File.ReadAllLines("/proc/stat"); foreach (string line in lines) { if (line.StartsWith("cpu ")) { string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string cpuName = parts[0]; // "cpu" long[] currentValues = new long[parts.Length - 1]; for (int i = 1; i < parts.Length; i++) { currentValues[i - 1] = long.Parse(parts[i]); } if (!previousCpuTimes.TryGetValue(cpuName, out var previousValues)) { previousCpuTimes[cpuName] = currentValues; return 0; // 第一次读取无结果 } previousCpuTimes[cpuName] = currentValues; long prevTotal = Sum(previousValues); long currTotal = Sum(currentValues); long prevIdle = previousValues[3]; // idle long currIdle = currentValues[3]; long totalDiff = currTotal - prevTotal; long idleDiff = currIdle - prevIdle; double cpuUsage = (double)(totalDiff - idleDiff) / totalDiff * 100; return cpuUsage; } } return 0; } // macOS: 使用 top 命令 static double GetCpuUsageMacOS() { try { var start = GetCpuUsageFromTop(); Thread.Sleep(500); var end = GetCpuUsageFromTop(); return end - start; } catch { return 0; } } static double GetCpuUsageFromTop() { var process = new Process { StartInfo = new ProcessStartInfo { FileName = "top", Arguments = "-l 1 -n 0", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; process.Start(); string output = process.StandardOutput.ReadToEnd(); process.WaitForExit(); string[] lines = output.Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (string line in lines) { if (line.Contains("CPU usage")) { // 示例:CPU usage: 5.3% user, 2.1% sys, 92.6% idle int userIndex = line.IndexOf("user", StringComparison.Ordinal); int sysIndex = line.IndexOf("sys", StringComparison.Ordinal); if (userIndex > 0 && sysIndex > 0) { string userStr = line.Substring(line.IndexOf(':') + 1, userIndex - line.IndexOf(':') - 1).Trim(); string sysStr = line.Substring(userIndex + 5, sysIndex - (userIndex + 5)).Trim(); if (double.TryParse(userStr.Replace("%", ""), out double user) && double.TryParse(sysStr.Replace("%", ""), out double sys)) { return user + sys; } } } } return 0; } static long Sum(long[] values) { long total = 0; foreach (var v in values) { total += v; } return total; } }
08-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值