Commit 9debb6c4 authored by Ph. SW.'s avatar Ph. SW.

Add how to get CPU frequencies in C

* by reading /proc/cpuinfo
* by using likwid
parent 47d179c3
## get-cpu-freq
This code illustrates how to get current average frequency of all cores, by executing a shell command, which reads content of `/proc/cpuinfo`.
So this code is also an example of usage of `popen()`.
## likwid-freq
This code illustrates how to get current frequency of a given core and how to get the uncore frequency of a given socket with the library [likwid](https://hpc.fau.de/research/tools/likwid/)
// From https://stackoverflow.com/a/31722775
/* How to know if Intel's turboboost is enabled:
* cat /sys/devices/system/cpu/intel_pstate/no_turbo
* 0 => turbo boost on, off otherwise
* (from https://askubuntu.com/a/991839)
*/
#include <stdio.h>
double get_cpu_freq() {
FILE *cmd = popen("grep 'pu MHz' /proc/cpuinfo | cut -d : -f 2 | awk '{ total += $1; count++ } END { print total/count }'", "r");
if (cmd == NULL)
return -1;
size_t n;
char buff[8];
double cpu_freq = -1;
if ((n = fread(buff, 1, sizeof(buff)-1, cmd)) <= 0)
return -1;
buff[n] = '\0';
if (sscanf(buff, "%lf", &cpu_freq) != 1)
return -1;
pclose(cmd);
return cpu_freq;
}
int main(void) {
double cpu_freq = get_cpu_freq();
if (cpu_freq == -1)
fprintf(stderr, "Error retrieving cpu freq\n");
else
printf("CPU freq: %lf\n", cpu_freq);
return 0;
}
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <signal.h>
#include <likwid.h>
static int sleeptime = 1;
static int run = 1;
void INThandler(int sig)
{
signal(sig, SIG_IGN);
run = 0;
}
int main (int argc, char* argv[])
{
int c;
topology_init();
CpuTopology_t cputopo = get_cpuTopology();
signal(SIGINT, INThandler);
while (run)
{
sleep(sleeptime);
for (c = 0; c < cputopo->numHWThreads; c++)
{
printf("cpu=%d freq = %lu MHz\n", c, freq_getCpuClockCurrent(c) / 1000);
}
for (c = 0; c < cputopo->numSockets; c++)
{
printf("core=%d uncore freq = %lu MHz\n", c, freq_getUncoreFreqCur(c));
}
printf("\n");
}
monitor_exit:
topology_finalize();
return 0;
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment