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
下载前必看:https://pan.quark.cn/s/a4b39357ea24 在本资料中,将阐述如何运用JavaScript达成单击下拉列表框选定选项后即时转向对应页面的功能。 此种技术适用于网页布局中用户需迅速选取并转向不同页面的情形,诸如网站导航栏或内容目录等场景。 达成此功能,能够显著改善用户交互体验,精简用户的操作流程。 我们须熟悉HTML里的`<select>`组件,该组件用于构建一个选择列表。 用户可从中选定一项,并可引发一个事件来响应用户的这一选择动作。 在本次实例中,我们借助`onchange`事件监听器来实现当用户在下拉列表框中选定某个选项时,页面能自动转向该选项关联的链接地址。 JavaScript里的`window.location`属性旨在获取或设定浏览器当前载入页面的网址,通过变更该属性的值,能够实现页面的转向。 在本次实例的实现方案里,运用了`eval()`函数来动态执行字符串表达式,这在现代的JavaScript开发实践中通常不被推荐使用,因为它可能诱发安全问题及难以排错的错误。 然而,为了本例的简化展示,我们暂时搁置这一问题,因为在更复杂的实际应用中,可选用其他方法,例如ES6中的模板字符串或其他函数来安全地构建和执行字符串。 具体到本例的代码实现,`MM_jumpMenu`函数负责处理转向逻辑。 它接收三个参数:`targ`、`selObj`和`restore`。 其中`targ`代表要转向的页面,`selObj`是触发事件的下拉列表框对象,`restore`是标志位,用以指示是否需在转向后将下拉列表框的选项恢复至默认的提示项。 函数的实现通过获取`selObj`中当前选定的`selectedIndex`对应的`value`属性值,并将其赋予`...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值