perf(replication): replicate number accordion to cpu usage

This commit is contained in:
Alexey Kasyanchuk
2018-08-06 17:18:52 +03:00
parent 701a3008ca
commit 35f7d33e8f
2 changed files with 56 additions and 1 deletions

View File

@ -4,6 +4,7 @@ const compareVersions = require('compare-versions');
const getTorrent = require('./gettorrent') const getTorrent = require('./gettorrent')
const _ = require('lodash') const _ = require('lodash')
const asyncForEach = require('./asyncForEach') const asyncForEach = require('./asyncForEach')
const cpuUsage = require('./bt/cpu-usage-global')
module.exports = async ({ module.exports = async ({
sphinx, sphinx,
@ -213,7 +214,10 @@ module.exports = async ({
if(sphinxSingle.state === 'disconnected') if(sphinxSingle.state === 'disconnected')
return return
sphinxSingle.query('SELECT * FROM `torrents` ORDER BY rand() limit 5', (error, torrents) => { const cpu = cpuUsage()
const limit = Math.max(1, 5 - (cpu / 20) | 0)
sphinxSingle.query(`SELECT * FROM torrents ORDER BY rand() limit ${limit}`, (error, torrents) => {
if(!torrents || torrents.length == 0) { if(!torrents || torrents.length == 0) {
callback(undefined) callback(undefined)
return; return;

View File

@ -0,0 +1,51 @@
var os = require("os");
//Create function to get CPU information
function cpuAverage() {
//Initialise sum of idle and time of cores and fetch CPU info
let totalIdle = 0, totalTick = 0;
const cpus = os.cpus();
//Loop through CPU cores
for(let i = 0, len = cpus.length; i < len; i++) {
//Select CPU core
const cpu = cpus[i];
//Total up the time in the cores tick
for(const type in cpu.times) {
totalTick += cpu.times[type];
}
//Total up the idle time of the core
totalIdle += cpu.times.idle;
}
//Return the average Idle and Tick times
return {idle: totalIdle / cpus.length, total: totalTick / cpus.length};
}
//Grab first CPU Measure
let startMeasure = cpuAverage();
let percentageCPU = 0
//Set delay for second Measure
const cpuTimer = setInterval(function() {
//Grab second Measure
const endMeasure = cpuAverage();
//Calculate the difference in idle and total time between the measures
const idleDifference = endMeasure.idle - startMeasure.idle;
const totalDifference = endMeasure.total - startMeasure.total;
//Calculate the average percentage CPU usage
percentageCPU = 100 - ~~(100 * idleDifference / totalDifference);
startMeasure = endMeasure
}, 300);
cpuTimer.unref()
module.exports = () => percentageCPU