You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
simulacion-permeabilidad/fftma_module/gen/lib_src/memory.c

93 lines
2.5 KiB
C

#include <sys/types.h>
#include <sys/sysinfo.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/times.h>
#include <sys/vtimes.h>
#include <unistd.h>
#include "log.h"
#include "memory.h"
static unsigned long long lastTotalUser, lastTotalUserLow, lastTotalSys, lastTotalIdle;
static clock_t lastCPU, lastSysCPU, lastUserCPU;
static int numProcessors;
void getTotalVirtualMem(double* total_ram) {
const double megabyte = 1024 * 1024;
struct sysinfo si;
sysinfo(&si);
*total_ram = si.totalram / megabyte;
}
void getVirtualMemUsed(double* used_ram) {
const double megabyte = 1024 * 1024;
struct sysinfo si;
sysinfo(&si);
*used_ram = (si.totalram - si.freeram) / megabyte;
}
int parseLine(char* line) {
// This assumes that a digit will be found and the line ends in " Kb".
int i = strlen(line);
const char* p = line;
while (*p <'0' || *p > '9') p++;
line[i-3] = '\0';
i = atoi(p);
return i;
}
int getVirtualMemUsedByCurrentProcess() {
FILE* file = fopen("/proc/self/status", "r");
int result = -1;
char line[128];
while (fgets(line, 128, file) != NULL){
if (strncmp(line, "VmSize:", 7) == 0){
result = parseLine(line);
break;
}
}
fclose(file);
return result / 1024;
}
void skip_lines(FILE *fp, int numlines) {
int cnt = 0;
char ch;
while ((cnt < numlines) && ((ch = getc(fp)) != EOF)) {
if (ch == '\n') cnt++;
}
}
void get_stats(struct cpustat *st, int cpunum) {
FILE *fp = fopen("/proc/stat", "r");
int lskip = cpunum+1;
skip_lines(fp, lskip);
char cpun[255];
fscanf(fp, "%s %d %d %d %d %d %d %d", cpun, &(st->t_user), &(st->t_nice),
&(st->t_system), &(st->t_idle), &(st->t_iowait), &(st->t_irq),
&(st->t_softirq));
fclose(fp);
return;
}
double calculate_load(struct cpustat *prev, struct cpustat *cur) {
int idle_prev = (prev->t_idle) + (prev->t_iowait);
int idle_cur = (cur->t_idle) + (cur->t_iowait);
int nidle_prev = (prev->t_user) + (prev->t_nice) + (prev->t_system) + (prev->t_irq) + (prev->t_softirq);
int nidle_cur = (cur->t_user) + (cur->t_nice) + (cur->t_system) + (cur->t_irq) + (cur->t_softirq);
int total_prev = idle_prev + nidle_prev;
int total_cur = idle_cur + nidle_cur;
double totald = (double) total_cur - (double) total_prev;
double idled = (double) idle_cur - (double) idle_prev;
double cpu_perc = (1000 * (totald - idled) / totald + 1) / 10;
return cpu_perc;
}