nodejs 計算記憶體使用率

dengxiacaidi8980發表於2015-10-17
//計算記憶體使用率
function calcMem(){
	let mem_total = os.totalmem(),
		mem_free = os.freemem(),
		mem_used = mem_total - mem_free,
		mem_ratio = 0;
	mem_total = (mem_total / (1024 * 1024 * 1024)).toFixed(1);
	mem_used = (mem_used / (1024 * 1024 * 1024)).toFixed(1);
	mem_ratio = parseInt(mem_used / mem_total * 100);
	return {
		total: mem_total,
		used: mem_used,
		ratio: mem_ratio
	}	
}

測試worker

'use strict';
const fork = require('child_process').fork,
	cpus = require('os').cpus();
//儲存被子程式例項陣列
var workers = {};
//這裡的被子程式理論上可以無限多
var appsPath = ['./os.js','./os.js','./os.js'];
var createWorker = function(appPath){
    //儲存fork返回的程式例項
    var worker = fork(appPath);
    //監聽子程式exit事件
    worker.on('exit',function(){
        console.log('worker: ' + worker.pid + ' exited');
        delete workers[worker.pid];
        createWorker(appPath);
    });
    workers[worker.pid] = worker;
    console.log('Create worker: ' + worker.pid);
}
//啟動所有子程式
for (var i = appsPath.length - 1; i >= 0; i--) {
    createWorker(appsPath[i]);
};
//父程式退出時殺死所有子程式
process.on('exit',function(){
    for(var pid in workers){
        workers[pid].kill();
    }
})

  

轉載於:https://www.cnblogs.com/zh33gl/p/4886746.html

相關文章