Skip to content

Instantly share code, notes, and snippets.

@lilydjwg
Last active May 10, 2020 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lilydjwg/98a2629529a4409438eccecbffa979a8 to your computer and use it in GitHub Desktop.
Save lilydjwg/98a2629529a4409438eccecbffa979a8 to your computer and use it in GitHub Desktop.
use-cpu: nothing but uses up one cpu core, printing out how much cpu time allocated to it every second
#include<stdio.h>
#include<sys/time.h>
#include<stdbool.h>
#include<signal.h>
#include<stdint.h>
#include<sys/resource.h>
volatile uint64_t count = 0;
void alarm_handler() {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
static struct timeval old_ut = {0, 0};
struct timeval ut = ru.ru_utime;
struct timeval diff;
timersub(&ut, &old_ut, &diff);
old_ut = ut;
double ms = diff.tv_sec * 1000 + diff.tv_usec / 1000.0;
static long old_nvcsw = 0;
static long old_nivcsw = 0;
long nvcsw = ru.ru_nvcsw - old_nvcsw;
old_nvcsw = ru.ru_nvcsw;
long nivcsw = ru.ru_nivcsw - old_nivcsw;
old_nivcsw = ru.ru_nivcsw;
printf("%12ld/s, %6.1fms, %ld+%ld switches\n",
count, ms, nvcsw, nivcsw);
count = 0;
}
int main(){
sigset_t set;
sigemptyset(&set);
struct sigaction act = {
.sa_handler = alarm_handler,
.sa_mask = set,
.sa_flags = 0,
.sa_restorer = NULL,
};
sigaction(SIGALRM, &act, NULL);
struct itimerval it = {
.it_interval = {
.tv_sec = 1,
.tv_usec = 0,
},
.it_value = {
.tv_sec = 1,
.tv_usec = 0,
}
};
setitimer(ITIMER_REAL, &it, NULL);
while(true) {
count++;
}
return 0;
}

This small program is for CPU scheduler testing. Note that the first number (the count) is of little use but I print it out still so the compiler won't do anything to the counting.

Compile with gcc -O2 -Wall -o use-cpu use-cpu.c. This is supposed to run only on Linux systems, and you can use taskset to pin it on specific CPU cores.

For related documentations, you can read manpages sched(7) and cgroups(7).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment