Skip to content

Instantly share code, notes, and snippets.

@syldrathecat
Created June 24, 2017 07:57
Show Gist options
  • Save syldrathecat/b801dc8c4d70ab69038cb0ae95827b12 to your computer and use it in GitHub Desktop.
Save syldrathecat/b801dc8c4d70ab69038cb0ae95827b12 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
static int limit_temp_mc = 65000;
static long long power_step_down_uw = -1000000;
static long long power_step_up_uw = 200000;
static long long power_limit_stock = 50000000;
static long long power_limit_min = 15000000;
static long long power_limit_uw = 50000000;
void set_power_limit_uw(long long uw)
{
char buf[255];
snprintf(buf, sizeof buf, "%lld", uw);
FILE* fh = fopen("/sys/devices/virtual/powercap/intel-rapl/intel-rapl:0/constraint_0_power_limit_uw", "wt");
if (fh)
{
fputs(buf, fh);
fclose(fh);
}
}
int read_number(const char* filename)
{
char buf[32];
FILE* hwmon = fopen(filename, "r");
int num = -1;
if (hwmon != NULL && fgets(buf, 32, hwmon))
{
sscanf(buf, "%d", &num);
fclose(hwmon);
}
return num;
}
int main()
{
char buf[255];
set_power_limit_uw(power_limit_uw);
while (1)
{
limit_temp_mc = read_number("/tmp/cpu_temp") * 1000;
if (limit_temp_mc <= 0)
limit_temp_mc = 65000;
else if (limit_temp_mc >= 70000)
limit_temp_mc = 70000;
else if (limit_temp_mc < 30000)
limit_temp_mc = 30000;
FILE* hwmon = fopen("/sys/class/hwmon/hwmon2/temp1_input", "r");
int cpu_temp_mc = -1;
if (hwmon != NULL && fgets(buf, 255, hwmon))
{
sscanf(buf, "%d", &cpu_temp_mc);
}
if (hwmon != NULL) fclose(hwmon);
if (cpu_temp_mc == -1 || cpu_temp_mc > limit_temp_mc)
{
power_limit_uw += power_step_down_uw * ((cpu_temp_mc - limit_temp_mc + 999) / 1000);
if (power_limit_uw < power_limit_min)
power_limit_uw = power_limit_min;
set_power_limit_uw(power_limit_uw);
}
else if (cpu_temp_mc < limit_temp_mc && power_limit_uw < power_limit_stock)
{
power_limit_uw += power_step_up_uw * ((limit_temp_mc - cpu_temp_mc + 999) / 1000);
if (power_limit_uw > power_limit_stock)
power_limit_uw = power_limit_stock;
set_power_limit_uw(power_limit_uw);
}
usleep(1000000);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment