timers/cpu_burner.c

This is timers/cpu_burner.c, an example to accompany the book, The Linux Programming Interface.

This file is not printed in the book; it is a supplementary file for Chapter 23.

The source code file is copyright 2024, Michael Kerrisk, and is licensed under the GNU General Public License, version 3.

In the listing below, the names of Linux system calls and C library functions are hyperlinked to manual pages from the Linux man-pages project, and the names of functions implemented in the book are hyperlinked to the implementations of those functions.

 

Download timers/cpu_burner.c

  Cover of The Linux Programming Interface

Function list (Bold in this list means a function is not static)

/* cpu_burner.c

   A small program that simply consumes CPU time, displaying the rate of CPU
   consumption during each second.
*/
#include <time.h>
#include "tlpi_hdr.h"

#define NANO 1000000000L
static long
timespecDiff(struct timespec a, struct timespec b)
{
    return (b.tv_sec - a.tv_sec) * NANO + b.tv_nsec - a.tv_nsec;
}
int
main(int argc, char *argv[])
{
    struct timespec curr_real, prev_cpu;

    struct timespec prev_real;
    if (clock_gettime(CLOCK_REALTIME, &prev_real) == -1)
        errExit("clock_gettime");
    if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &prev_cpu) == -1)
        errExit("clock_gettime");

    /* Loop consuming CPU time. */

    int cnt = 0;
    while (1) {
        if (clock_gettime(CLOCK_REALTIME, &curr_real) == -1)
            errExit("clock_gettime");

        long elapsed_real_nsec = timespecDiff(prev_real, curr_real);

        /* Each time the real time clock ticks over to another second,
           display the rate of CPU consumption in the interval since the
           previous second. */

        if (elapsed_real_nsec >= NANO) {
            struct timespec curr_cpu;
            if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &curr_cpu) == -1)
                errExit("clock_gettime");

            long elapsed_cpu_nsec = timespecDiff(prev_cpu, curr_cpu);

            printf("[%ld]  %%CPU = %5.2f (%d)\n", (long) getpid(),
                    (double) elapsed_cpu_nsec / elapsed_real_nsec * 100.0,
                    cnt);

            prev_real = curr_real;
            prev_cpu = curr_cpu;
            cnt++;
        }
    }

    exit(EXIT_SUCCESS);
}

 

Download timers/cpu_burner.c

Note that, in most cases, the programs rendered in these web pages are not free standing: you'll typically also need a few other source files (mostly in the lib/ subdirectory) as well. Generally, it's easier to just download the entire source tarball and build the programs with make(1). By hovering your mouse over the various hyperlinked include files and function calls above, you can see which other source files this file depends on.

Valid XHTML 1.1