Skip to content

Instantly share code, notes, and snippets.



Last active May 10, 2020
What would you like to do?
use-cpu: nothing but uses up one cpu core, printing out how much cpu time allocated to it every second
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;
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) {
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
You can’t perform that action at this time.