diff --git a/src/background/api.js b/src/background/api.js index f7b0ce3..81d68aa 100644 --- a/src/background/api.js +++ b/src/background/api.js @@ -4,6 +4,7 @@ const compareVersions = require('compare-versions'); const getTorrent = require('./gettorrent') const _ = require('lodash') const asyncForEach = require('./asyncForEach') +const cpuUsage = require('./bt/cpu-usage-global') module.exports = async ({ sphinx, @@ -213,7 +214,10 @@ module.exports = async ({ if(sphinxSingle.state === 'disconnected') 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) { callback(undefined) return; diff --git a/src/background/bt/cpu-usage-global.js b/src/background/bt/cpu-usage-global.js new file mode 100644 index 0000000..3d1a5b2 --- /dev/null +++ b/src/background/bt/cpu-usage-global.js @@ -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 \ No newline at end of file