Skip to content

Instantly share code, notes, and snippets.

@sidwarkd
Last active December 22, 2023 14:23
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save sidwarkd/9578213 to your computer and use it in GitHub Desktop.
Save sidwarkd/9578213 to your computer and use it in GitHub Desktop.
Python and NodeJS example code for getting memory and cpu usage information on the Raspberry Pi
'use strict'
// A very simple nodeJS script that demonstrates how you can access
// memory usage information similar to how free -m works on the
// Raspberry Pi. Goes with µCast #14. http://youtu.be/EqyVlTP4R5M
// Usage: node pi_mem.js
// Example Output
//
// total used free cached
// 469 65 404 31
// Memory Usage: 7%
var fs = require('fs');
var PiStats = function(){
var memInfo = {};
var currentCPUInfo = {total:0, active:0};
var lastCPUInfo = {total:0, active:0};
function getValFromLine(line){
var match = line.match(/[0-9]+/gi);
if(match !== null)
return parseInt(match[0]);
else
return null;
}
var getMemoryInfo = function(cb){
fs.readFile('/proc/meminfo', 'utf8', function(err, data){
if(err){
cb(err);
return;
}
var lines = data.split('\n');
memInfo.total = Math.floor(getValFromLine(lines[0]) / 1024);
memInfo.free = Math.floor(getValFromLine(lines[1]) / 1024);
memInfo.cached = Math.floor(getValFromLine(lines[3]) / 1024);
memInfo.used = memInfo.total - memInfo.free;
memInfo.percentUsed = Math.ceil(((memInfo.used - memInfo.cached) / memInfo.total) * 100);
cb(null, memInfo);
});
};
var calculateCPUPercentage = function(oldVals, newVals){
var totalDiff = newVals.total - oldVals.total;
var activeDiff = newVals.active - oldVals.active;
return Math.ceil((activeDiff / totalDiff) * 100);
};
var getCPUInfo = function(cb){
lastCPUInfo.active = currentCPUInfo.active;
lastCPUInfo.idle = currentCPUInfo.idle;
lastCPUInfo.total = currentCPUInfo.total;
fs.readFile('/proc/stat', 'utf8', function(err, data){
if(err){
if(cb !== undefined)
cb(err);
return;
}
var lines = data.split('\n');
var cpuTimes = lines[0].match(/[0-9]+/gi);
currentCPUInfo.total = 0;
// We'll count both idle and iowait as idle time
currentCPUInfo.idle = parseInt(cpuTimes[3]) + parseInt(cpuTimes[4]);
for (var i = 0; i < cpuTimes.length; i++){
currentCPUInfo.total += parseInt(cpuTimes[i]);
}
currentCPUInfo.active = currentCPUInfo.total - currentCPUInfo.idle
currentCPUInfo.percentUsed = calculateCPUPercentage(lastCPUInfo, currentCPUInfo);
if(cb !== undefined)
cb(null, currentCPUInfo);
});
};
return{
getMemoryInfo: getMemoryInfo,
getCPUInfo: getCPUInfo,
printMemoryInfo: function(){
getMemoryInfo(function(err, data){
console.log("total\tused\tfree\tcached");
console.log( data.total + "\t" + data.used + "\t" + data.free + "\t" + data.cached );
console.log("Memory Usage:\t" + data.percentUsed + "%");
});
},
printCPUInfo: function(){
getCPUInfo(function(err, data){
console.log("Current CPU Usage: " + data.percentUsed + "%");
});
}
};
}();
PiStats.printMemoryInfo();
console.log("")
setInterval(PiStats.printCPUInfo, 1000);
# A very simple python script that demonstrates how you can access
# memory and cpu usage information similar to how free and top
# work on the Raspberry Pi. Goes with uCast #14 and #15.
# Usage: python pi_stats.py
import re, time, sys
class PiStats(object):
def __init__(self):
self.total_memory = None
self.free_memory = None
self.cached_memory = None
self.lastCPUInfo = {'total':0, 'active':0}
self.currentCPUInfo = {'total':0, 'active':0}
self.temp_in_celsius = None
def calculate_cpu_percentage(self):
total_diff = self.currentCPUInfo['total'] - self.lastCPUInfo['total']
active_diff = self.currentCPUInfo['active'] - self.lastCPUInfo['active']
return round(float(active_diff) / float(total_diff), 3) * 100.00
def update_stats(self):
# Read memory usage from /proc/meminfo
with open('/proc/meminfo', 'r') as mem_file:
# Remove the text description, kB, and whitespace before
# turning file lines into an int
for i, line in enumerate(mem_file):
if i == 0: # Total line
self.total_memory = int(line.strip("MemTotal: \tkB\n")) / 1024
elif i == 1: # Free line
self.free_memory = int(line.strip("MemFree: \tkB\n")) / 1024
elif i == 3: # Cached line
self.cached_memory = int(line.strip("Cached: \tkB\n")) / 1024
self.lastCPUInfo['total'] = self.currentCPUInfo['total']
self.lastCPUInfo['active'] = self.currentCPUInfo['active']
self.currentCPUInfo['total'] = 0
with open('/proc/stat', 'r') as cpu_file:
for i, line in enumerate(cpu_file):
if i == 0:
cpuStats = re.findall('([0-9]+)', line.strip())
self.currentCPUInfo['idle'] = int(cpuStats[3]) + int(cpuStats[4])
for t in cpuStats:
self.currentCPUInfo['total'] += int(t)
self.currentCPUInfo['active'] = self.currentCPUInfo['total'] - self.currentCPUInfo['idle']
self.currentCPUInfo['percent'] = self.calculate_cpu_percentage()
def get_memory_info(self):
# In linux the cached memory is available for program use so we'll
# include it in the free amount when calculating the usage percent
used_val = (self.total_memory - self.free_memory)
free_val = (self.free_memory)
percent_val = float(used_val - self.cached_memory) / float(self.total_memory)
return {'total': self.total_memory, 'cached': self.cached_memory, 'used': used_val, 'free': free_val, 'percent': round(percent_val, 3) * 100.00 }
def get_cpu_info(self):
return self.currentCPUInfo
stats = PiStats()
stats.update_stats()
meminfo = stats.get_memory_info()
print "total\tused\tfree\tcached"
print "%i\t%i\t%i\t%i"%(meminfo['total'],meminfo['used'],meminfo['free'],meminfo['cached'])
print "Memory Usage:\t%i%%"%(meminfo['percent'])
print "\n"
try:
while True:
cpu_info = stats.get_cpu_info()
print "CPU Usage:\t%i%%"%(cpu_info['percent'])
time.sleep(2);
stats.update_stats()
except KeyboardInterrupt:
print "Exiting.\n"
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment