linux_cpuload.hpp
Go to the documentation of this file.
1/**
2 * @author: Daniel Fuchs
3 * @contact: fuxeysolutions@gmail.com
4 *
5 * distributed under the MIT License (MIT).
6 * Copyright (c) Daniel Fuchs
7 *
8 */
9#pragma once
10
11#include <chrono>
12#include <map>
13#include <string>
14#include <tuple>
15#include <unordered_map>
16#include <vector>
17
19{
20
21public:
22 cpuLoad() = delete;
23 /**
24 * @brief constructor
25 * @param procFileName
26 */
27 explicit cpuLoad(std::string procFileName = "/proc/stat") :
28 procFile(std::move(procFileName)), cpuName(""){};
29
30 /**
31 * @brief initialize the parsing algo
32 */
33 void initCpuUsage();
34 /**
35 * @brief get current cpu load in 0-100%
36 * @return current cpu load
37 */
38 double getCurrentCpuUsage();
39
40 /**
41 * @brief get Cpu user / nice / system /idle time. used for cpu usage per process
42 * @return tuple<user,nice,system,idle>
43 */
44 std::tuple<uint64_t, uint64_t, uint64_t, uint64_t>
46 {
47 auto cpuLoad_ = this->parseStatFile(this->procFile);
48 return std::make_tuple(cpuLoad_.at("cpu").at("user"),
49 cpuLoad_.at("cpu").at("nice"),
50 cpuLoad_.at("cpu").at("system"),
51 cpuLoad_.at("cpu").at("idle"));
52 }
53
54 /**
55 * @brief get cpu Usage of all cores in percent
56 * @return vector of cpu load per core 0-100%
57 */
58 std::vector<double> getCurrentMultiCoreUsage();
59 /**
60 * @brief get CPU Description
61 * @param cpuNameFile - typical /proc/cpuinfo
62 * @return cpu Type string
63 */
64 std::string getCPUName(const std::string& cpuNameFile = "/proc/cpuinfo");
65
66private:
67 void calculateCpuUsage();
68 std::map<std::string, std::unordered_map<std::string, uint64_t>>
69 parseStatFile(const std::string& fileName);
70 void upDateCPUUsage();
71 std::chrono::system_clock::time_point currentTime;
72 std::string procFile;
73 std::string cpuName;
74 std::map<std::string, double> cpuUsage;
75 std::map<std::string, std::unordered_map<std::string, uint64_t>> cpuLoadMap;
76 std::map<std::string, std::unordered_map<std::string, uint64_t>> oldCpuLoadMap;
77};
std::string getCPUName(const std::string &cpuNameFile="/proc/cpuinfo")
get CPU Description
double getCurrentCpuUsage()
get current cpu load in 0-100%
std::tuple< uint64_t, uint64_t, uint64_t, uint64_t > getCpuTimes()
get Cpu user / nice / system /idle time.
void initCpuUsage()
initialize the parsing algo
cpuLoad(std::string procFileName="/proc/stat")
constructor
cpuLoad()=delete
std::vector< double > getCurrentMultiCoreUsage()
get cpu Usage of all cores in percent