Skip to content

Instantly share code, notes, and snippets.

@Twinklebear
Last active June 4, 2018 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Twinklebear/490a7dbdb35ce7fdd1836240fa2256b7 to your computer and use it in GitHub Desktop.
Save Twinklebear/490a7dbdb35ce7fdd1836240fa2256b7 to your computer and use it in GitHub Desktop.
linux performance tracking utility
#include <iostream>
#include <thread>
#include <chrono>
#include <sys/times.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/resource.h>
#include <unistd.h>
#include <fstream>
using namespace std::chrono;
rusage prevUsage = {0};
rusage curUsage = {0};
high_resolution_clock::time_point prevWall, curWall;
size_t frameNumber = 0;
void logProcessStatistics(std::ostream &os) {
const double elapsedCpu = curUsage.ru_utime.tv_sec + curUsage.ru_stime.tv_sec
- (prevUsage.ru_utime.tv_sec + prevUsage.ru_stime.tv_sec)
+ 1e-6f * (curUsage.ru_utime.tv_usec + curUsage.ru_stime.tv_usec
- (prevUsage.ru_utime.tv_usec + prevUsage.ru_stime.tv_usec));
const double elapsedWall = duration_cast<duration<double>>(curWall - prevWall).count();
os << "\tCPU: " << elapsedCpu / elapsedWall * 100.0 << "%\n";
std::ifstream procStatus("/proc/" + std::to_string(getpid()) + "/status");
std::string line;
const static std::string threadPrefix = "Threads:";
const static std::string cpusPrefix = "Cpus_allowed_list:";
while (std::getline(procStatus, line)) {
if (line.compare(0, threadPrefix.size(), threadPrefix) == 0) {
os << "\t" << line << "\n";
} else if (line.compare(0, cpusPrefix.size(), cpusPrefix) == 0) {
os << "\t" << line << "\n";
}
}
}
int main() {
getrusage(RUSAGE_SELF, &prevUsage);
prevWall = high_resolution_clock::now();
// Do something expensive that you want to profile
std::this_thread::sleep_for(seconds(1));
getrusage(RUSAGE_SELF, &curUsage);
curWall = high_resolution_clock::now();
logProcessStatistics(std::cout);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment