I've arrived at a similar solution, but your solution, as far as I can see, will give the avarage load since the computer started.
Now I'm reading /proc/stat twice with a small interval inbetween, and measure the difference between the two. This is the actuall CPU load (hopefully). I'll try to post a working soltuion for future use when I finish it.
Here is the code I came up with.
Sometimes it gives values slightly negative. I think this can be accounted for the inaccuracy of the time measurement, or the /proc/stat file.
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/date_time.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
//This function reads /proc/stat and returns the idle value for each cpu in a vector
std::vector<longlong> get_idle() {
//Virtual file, created by the Linux kernel on demand
std::ifstream in( "/proc/stat" );
std::vector<longlong> result;
//This might broke if there are not 8 columns in /proc/stat
boost::regex reg("cpu(\\d+) (\\d+) (\\d+) (\\d+) (\\d+) (\\d+) (\\d+) (\\d+) (\\d+)");
std::string line;
while ( std::getline(in, line) ) {
boost::smatch match;
if ( boost::regex_match( line, match, reg ) ) {
longlong idle_time = boost::lexical_cast<longlong>(match[5]);
result.push_back( idle_time );
}
}
return result;
}
//This function returns the avarege load in the next interval_seconds for each cpu in a vector
//get_load() halts this thread for interval_seconds
std::vector<float> get_load(unsigned interval_seconds) {
boost::posix_time::ptime current_time_1 = boost::date_time::microsec_clock<boost::posix_time::ptime>::universal_time();
std::vector<longlong> idle_time_1 = get_idle();
sleep(interval_seconds);
boost::posix_time::ptime current_time_2 = boost::date_time::microsec_clock<boost::posix_time::ptime>::universal_time();
std::vector<longlong> idle_time_2 = get_idle();
//We have to measure the time, beacuse sleep is not accurate
constfloat total_seconds_elpased = float((current_time_2 - current_time_1).total_milliseconds()) / 1000.f;
std::vector<float> cpu_loads;
for ( unsigned i = 0; i < idle_time_1.size(); ++i ) {
//This might get slightly negative, because our time measurment is not accurate
constfloat load = 1.f - float(idle_time_2[i] - idle_time_1[i])/(100.f * total_seconds_elpased);
cpu_loads.push_back( load );
}
return cpu_loads;
}
int main() {
constunsigned measurement_count = 5;
constunsigned interval_seconds = 5;
for ( unsigned i = 0; i < measurement_count; ++i ) {
std::vector<float> cpu_loads = get_load(interval_seconds);
for ( unsigned i = 0; i < cpu_loads.size(); ++i ) {
std::cout << "cpu " << i << " : " << cpu_loads[i] * 100.f << "%" << std::endl;
}
}
return 0;
}
Hmmm....never thought much about CPU usage until you made this thread. Don't think any of my code taxes the CPU that bad though. I'll have to bookmark this for later reference :).