mmy / lib /CPUMonitor.ts
Mohammad Shahid
added major optimization for hf
54a11dd
// CPU monitoring utility for HuggingFace free tier
class CPUMonitor {
private cpuUsageHistory: number[] = [];
private maxCpuThreshold = 80; // Maximum CPU percentage before throttling
private throttleActive = false;
constructor() {
this.startMonitoring();
}
private startMonitoring() {
if (typeof window === 'undefined') return; // Server-side only
setInterval(() => {
this.checkCPUUsage();
}, 1000); // Check every second
}
private async checkCPUUsage() {
// Simple CPU usage estimation based on frame timing
const start = performance.now();
await new Promise(resolve => setTimeout(resolve, 10));
const duration = performance.now() - start;
// If tasks take longer than expected, assume high CPU
const estimatedCPU = Math.min(100, (duration / 10) * 100);
this.cpuUsageHistory.push(estimatedCPU);
if (this.cpuUsageHistory.length > 5) {
this.cpuUsageHistory.shift();
}
const avgCPU = this.cpuUsageHistory.reduce((a, b) => a + b, 0) / this.cpuUsageHistory.length;
if (avgCPU > this.maxCpuThreshold && !this.throttleActive) {
console.warn(`[CPU Monitor] High CPU usage detected: ${avgCPU.toFixed(1)}%. Activating throttling.`);
this.activateThrottling();
} else if (avgCPU < this.maxCpuThreshold * 0.7 && this.throttleActive) {
console.log(`[CPU Monitor] CPU usage normalized: ${avgCPU.toFixed(1)}%. Deactivating throttling.`);
this.deactivateThrottling();
}
}
private activateThrottling() {
this.throttleActive = true;
// Dispatch event for components to react
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('cpu-throttle-active'));
}
}
private deactivateThrottling() {
this.throttleActive = false;
if (typeof window !== 'undefined') {
window.dispatchEvent(new CustomEvent('cpu-throttle-inactive'));
}
}
public isThrottling(): boolean {
return this.throttleActive;
}
public getCurrentCPU(): number {
return this.cpuUsageHistory[this.cpuUsageHistory.length - 1] || 0;
}
}
export const cpuMonitor = new CPUMonitor();