Skip to content

Instantly share code, notes, and snippets.

@stevedoyle
Last active February 12, 2024 01:01
Show Gist options
  • Save stevedoyle/1319053 to your computer and use it in GitHub Desktop.
Save stevedoyle/1319053 to your computer and use it in GitHub Desktop.
Get CPU frequency (Linux platforms - /proc/cpuinfo)
#include <iostream>
#include <fstream>
#include <string>
#include <stdint.h>
#include <pcre.h>
using namespace std;
uint32_t cpufreq()
{
uint32_t cpuFreq = 0;
// CPU frequency is stored in /proc/cpuinfo in lines beginning with "cpu MHz"
string pattern = "^cpu MHz\\s*:\\s*(\\d+)";
const char* pcreErrorStr = NULL;
int pcreErrorOffset = 0;
pcre* reCompiled = pcre_compile(pattern.c_str(), PCRE_ANCHORED, &pcreErrorStr,
&pcreErrorOffset, NULL);
if(reCompiled == NULL)
{
return 0;
}
ifstream ifs("/proc/cpuinfo");
if(ifs.is_open())
{
string line;
int results[10];
while(ifs.good())
{
getline(ifs, line);
int rc = pcre_exec(reCompiled, 0, line.c_str(), line.length(),
0, 0, results, 10);
if(rc < 0)
continue;
// Match found - extract frequency
const char* matchStr = NULL;
pcre_get_substring(line.c_str(), results, rc, 1, &(matchStr));
cpuFreq = atol(matchStr);
pcre_free_substring(matchStr);
break;
}
}
ifs.close();
pcre_free(reCompiled);
return cpuFreq;
}
int main()
{
cout << "CPU Frequency = " << cpufreq() << " MHz" << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment