(Micro)​benchmarking Linux kernel functions

Vincent Bernat

Usu­ally, the per­for­mance of a Linux sub­sys­tem is mea­sured through an ex­ter­nal (lo­cal or re­mote) process stress­ing it. De­pend­ing on the in­put point used, a large por­tion of code may be in­volved. To bench­mark a sin­gle func­tion, one so­lu­tion is to write a ker­nel module.

Minimal kernel module#

Sup­pose we want to bench­mark the IPv4 route lookup func­tion, fib_​lookup(). The fol­low­ing ker­nel func­tion ex­e­cutes 1,000 lookups for 8.8.8.8 and re­turns the av­er­age value.1 It uses the get_​cycles() func­tion to com­pute the ex­e­cu­tion “time.”

/* Execute a benchmark on fib_lookup() and put
   result into the provided buffer `buf`. */
static int do_bench(char *buf)
{
    unsigned long long t1, t2;
    unsigned long long total = 0;
    unsigned long i;
    unsigned count = 1000;
    int err = 0;
    struct fib_result res;
    struct flowi4 fl4;

    memset(&fl4, 0, sizeof(fl4));
    fl4.daddr = in_aton("8.8.8.8");

    for (i = 0; i < count; i++) {
        t1 = get_cycles();
        err |= fib_lookup(&init_net, &fl4, &res, 0);
        t2 = get_cycles();
        total += t2 - t1;
    }
    if (err != 0)
        return scnprintf(buf, PAGE_SIZE, "err=%d msg=\"lookup error\"\n", err);
    return scnprintf(buf, PAGE_SIZE, "avg=%llu\n", total / count);
}

Now, we need to em­bed this func­tion in a ker­nel mod­ule. The fol­low­ing code reg­is­ters a sysfs di­rec­tory con­tain­ing a pseudo-file run. When a user queries this file, the mod­ule runs the bench­mark func­tion and re­turns the re­sult as content.

#define pr_fmt(fmt) "kbench: " fmt

#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/module.h>
#include <linux/inet.h>
#include <linux/timex.h>
#include <net/ip_fib.h>

/* When a user fetches the content of the "run" file, execute the
   benchmark function. */
static ssize_t run_show(struct kobject *kobj,
                        struct kobj_attribute *attr,
                        char *buf)
{
    return do_bench(buf);
}

static struct kobj_attribute run_attr = __ATTR_RO(run);
static struct attribute *bench_attributes[] = {
    &run_attr.attr,
    NULL
};
static struct attribute_group bench_attr_group = {
    .attrs = bench_attributes,
};
static struct kobject *bench_kobj;

int init_module(void)
{
    int rc;
    /* ❶ Create a simple kobject named "kbench" in /sys/kernel. */
    bench_kobj = kobject_create_and_add("kbench", kernel_kobj);
    if (!bench_kobj)
        return -ENOMEM;

    /* ❷ Create the files associated with this kobject. */
    rc = sysfs_create_group(bench_kobj, &bench_attr_group);
    if (rc) {
        kobject_put(bench_kobj);
        return rc;
    }

    return 0;
}

void cleanup_module(void)
{
    kobject_put(bench_kobj);
}

/* Metadata about this module */
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Microbenchmark for fib_lookup()");

In ❶, kobject_​create_​and_​add() cre­ates a new kobject named kbench. A kobject is the ab­strac­tion be­hind the sysfs filesys­tem. This new kobject is vis­i­ble as the /sys/​kernel/​kbench/ di­rectory.

In ❷, sysfs_​create_​group() at­taches a set of at­tributes to our kobject. These at­tributes are ma­te­ri­al­ized as files in­side /sys/​kernel/​kbench/. Cur­rently, we de­clare only one of them, run, with the __ATTR_RO macro. The at­tribute is there­fore read-only (0444) and when a user tries to fetch the con­tent of the file, the run_​show() func­tion is in­voked with a buf­fer of PAGE_​SIZE bytes as last ar­gu­ment and is ex­pected to re­turn the num­ber of bytes written.

For more de­tails, you can look at the doc­u­men­ta­tion in the ker­nel and the as­so­ci­ated ex­am­ple. Be­ware, ran­dom posts found on the web (in­clud­ing this one) may be outdated.2

The fol­low­ing Makefile will com­pile this example:

# Kernel module compilation
KDIR = /lib/modules/$(shell uname -r)/build
obj-m += kbench_mod.o
kbench_mod.ko: kbench_mod.c
    make -C $(KDIR) M=$(PWD) modules

Af­ter ex­e­cut­ing make, you should get a kbench_​mod.ko file:

$ modinfo kbench_mod.ko
filename:       /home/bernat/code/…/kbench_mod.ko
description:    Microbenchmark for fib_lookup()
license:        GPL
depends:
name:           kbench_mod
vermagic:       4.14.0-1-amd64 SMP mod_unload modversions

You can load it and ex­e­cute the benchmark:

$ insmod ./kbench_mod.ko
$ ls -l /sys/kernel/kbench/run
-r--r--r-- 1 root root 4096 déc.  10 16:05 /sys/kernel/kbench/run
$ cat /sys/kernel/kbench/run
avg=75

The re­sult is a num­ber of cy­cles. You can get an ap­prox­i­mate time in nanosec­onds if you di­vide it by the fre­quency of your pro­ces­sor in gi­ga­hertz (25 ns if you have a 3 GHz pro­cessor).3

Configurable parameters#

The mod­ule hard-codes two con­stants: the num­ber of loops and the des­ti­na­tion ad­dress to test. We can make these pa­ram­e­ters user-con­fig­urable by ex­pos­ing them as at­tributes of our kobject and defin­ing a pair of func­tions to read/write them:

static unsigned long loop_count      = 5000;
static u32           flow_dst_ipaddr = 0x08080808;

/* A mutex is used to ensure we are thread-safe when altering attributes. */
static DEFINE_MUTEX(kb_lock);

/* Show the current value for loop count. */
static ssize_t loop_count_show(struct kobject *kobj,
                               struct kobj_attribute *attr,
                               char *buf)
{
    ssize_t res;
    mutex_lock(&kb_lock);
    res = scnprintf(buf, PAGE_SIZE, "%lu\n", loop_count);
    mutex_unlock(&kb_lock);
    return res;
}

/* Store a new value for loop count. */
static ssize_t loop_count_store(struct kobject *kobj,
                                struct kobj_attribute *attr,
                                const char *buf,
                                size_t count)
{
    unsigned long val;
    int err = kstrtoul(buf, 0, &val);
    if (err < 0)
        return err;
    if (val < 1)
        return -EINVAL;
    mutex_lock(&kb_lock);
    loop_count = val;
    mutex_unlock(&kb_lock);
    return count;
}

/* Show the current value for destination address. */
static ssize_t flow_dst_ipaddr_show(struct kobject *kobj,
                                    struct kobj_attribute *attr,
                                    char *buf)
{
    ssize_t res;
    mutex_lock(&kb_lock);
    res = scnprintf(buf, PAGE_SIZE, "%pI4\n", &flow_dst_ipaddr);
    mutex_unlock(&kb_lock);
    return res;
}

/* Store a new value for destination address. */
static ssize_t flow_dst_ipaddr_store(struct kobject *kobj,
                                     struct kobj_attribute *attr,
                                     const char *buf,
                                     size_t count)
{
    mutex_lock(&kb_lock);
    flow_dst_ipaddr = in_aton(buf);
    mutex_unlock(&kb_lock);
    return count;
}

/* Define the new set of attributes. They are read/write attributes. */
static struct kobj_attribute loop_count_attr      = __ATTR_RW(loop_count);
static struct kobj_attribute flow_dst_ipaddr_attr = __ATTR_RW(flow_dst_ipaddr);
static struct kobj_attribute run_attr             = __ATTR_RO(run);
static struct attribute *bench_attributes[] = {
    &loop_count_attr.attr,
    &flow_dst_ipaddr_attr.attr,
    &run_attr.attr,
    NULL
};

The IPv4 ad­dress is stored as a 32-bit in­te­ger but dis­played and parsed us­ing the dot­ted quad no­ta­tion. The ker­nel pro­vides the ap­pro­pri­ate helpers for this task.

Af­ter this change, we have two new files in /sys/​kernel/​kbench. We can read the cur­rent val­ues and mod­ify them:

# cd /sys/kernel/kbench
# ls -l
-rw-r--r-- 1 root root 4096 déc.  10 19:10 flow_dst_ipaddr
-rw-r--r-- 1 root root 4096 déc.  10 19:10 loop_count
-r--r--r-- 1 root root 4096 déc.  10 19:10 run
# cat loop_count
5000
# cat flow_dst_ipaddr
8.8.8.8
# echo 9.9.9.9 > flow_dst_ipaddr
# cat flow_dst_ipaddr
9.9.9.9

We still need to al­ter the do_​bench() func­tion to make use of these pa­rameters:

static int do_bench(char *buf)
{
    /* … */
    mutex_lock(&kb_lock);
    count = loop_count;
    fl4.daddr = flow_dst_ipaddr;
    mutex_unlock(&kb_lock);

    for (i = 0; i < count; i++) {
        /* … */

Meaningful statistics#

Cur­rently, we only com­pute the av­er­age lookup time. This value is usu­ally in­adequate:

  • A small num­ber of out­liers can raise this value quite sig­nif­i­cantly. An out­lier can hap­pen be­cause we were pre­empted out of CPU while ex­e­cut­ing the bench­marked func­tion. This does not hap­pen of­ten if the func­tion ex­e­cu­tion time is short (less than a mil­lisec­ond), but when this hap­pens, the out­liers can be off by sev­eral mil­lisec­onds, which is enough to make the av­er­age in­ad­e­quate when most val­ues are sev­eral or­ders of mag­ni­tude smaller. For this rea­son, the me­dian usu­ally gives a bet­ter view.4

  • The dis­tri­bu­tion may be asym­met­ri­cal or have sev­eral lo­cal max­ima. It’s bet­ter to keep sev­eral per­centiles or even a dis­tri­bu­tion graph.

To be able to ex­tract mean­ing­ful sta­tis­tics, we store the re­sults in an array.

static int do_bench(char *buf)
{
    unsigned long long *results;
    /* … */

    results = kmalloc(sizeof(*results) * count, GFP_KERNEL);
    if (!results)
        return scnprintf(buf, PAGE_SIZE, "msg=\"no memory\"\n");

    for (i = 0; i < count; i++) {
        t1 = get_cycles();
        err |= fib_lookup(&init_net, &fl4, &res, 0);
        t2 = get_cycles();
        results[i] = t2 - t1;
    }

    if (err != 0) {
        kfree(results);
        return scnprintf(buf, PAGE_SIZE, "err=%d msg=\"lookup error\"\n", err);
    }
    /* Compute and display statistics */
    display_statistics(buf, results, count);

    kfree(results);
    return strnlen(buf, PAGE_SIZE);
}

Then, we need a helper func­tion to be able to com­pute per­centiles:

static unsigned long long percentile(int p,
                                     unsigned long long *sorted,
                                     unsigned count)
{
    int index = p * count / 100;
    int index2 = index + 1;
    if (p * count % 100 == 0)
        return sorted[index];
    if (index2 >= count)
        index2 = index - 1;
    if (index2 < 0)
        index2 = index;
    return (sorted[index] + sorted[index+1]) / 2;
}

This func­tion needs a sorted ar­ray as in­put. The ker­nel pro­vides a heap­sort func­tion, sort(), for this pur­pose. An­other use­ful value to have is the de­vi­a­tion from the me­dian. Here is a func­tion to com­pute the me­dian ab­so­lute de­viation:5

static unsigned long long mad(unsigned long long *sorted,
                              unsigned long long median,
                              unsigned count)
{
    unsigned long long *dmedian = kmalloc(sizeof(unsigned long long) * count,
                                          GFP_KERNEL);
    unsigned long long res;
    unsigned i;

    if (!dmedian) return 0;
    for (i = 0; i < count; i++) {
        if (sorted[i] > median)
            dmedian[i] = sorted[i] - median;
        else
            dmedian[i] = median - sorted[i];
    }
    sort(dmedian, count, sizeof(unsigned long long), compare_ull, NULL);
    res = percentile(50, dmedian, count);
    kfree(dmedian);
    return res;
}

With these two func­tions, we can pro­vide ad­di­tional sta­tistics:

static void display_statistics(char *buf,
                               unsigned long long *results,
                               unsigned long count)
{
    unsigned long long p95, p90, p50;

    sort(results, count, sizeof(*results), compare_ull, NULL);
    if (count == 0) {
        scnprintf(buf, PAGE_SIZE, "msg=\"no match\"\n");
        return;
    }

    p95 = percentile(95, results, count);
    p90 = percentile(90, results, count);
    p50 = percentile(50, results, count);
    scnprintf(buf, PAGE_SIZE,
          "min=%llu max=%llu count=%lu 95th=%llu 90th=%llu 50th=%llu mad=%llu\n",
          results[0],
          results[count - 1],
          count,
          p95,
          p90,
          p50,
          mad(results, p50, count));
}

Up­date (2018-01)

In­tel rec­om­mends look­ing at the min­i­mum if its vari­ance is small.

We can also ap­pend a graph of the dis­tri­bu­tion func­tion (and of the cu­mu­la­tive dis­tri­bu­tion function):

min=72 max=33364 count=100000 95th=154 90th=142 50th=112 mad=6
    value │                      ┊                         count
       72 │                                                   51
       77 │▒                                                3548
       82 │▒▒░░                                             4773
       87 │▒▒░░░░░                                          5918
       92 │░░░░░░░                                          1207
       97 │░░░░░░░                                           437
      102 │▒▒▒▒▒▒░░░░░░░░                                  12164
      107 │▒▒▒▒▒▒▒░░░░░░░░░░░░░░                           15508
      112 │▒▒▒▒▒▒▒▒▒▒▒░░░░░░░░░░░░░░░░░░░░░░               23014
      117 │▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░             6297
      122 │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░              905
      127 │▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░           3845
      132 │▒▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░       6687
      137 │▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░     4884
      142 │▒▒░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░   4133
      147 │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░  1015
      152 │░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░  1123

Benchmark validity#

While the bench­mark pro­duces some fig­ures, we may ques­tion their va­lid­ity. There are sev­eral traps when writ­ing a mi­crobenchmark:

Dead code
The com­piler may op­ti­mize away our bench­mark be­cause the re­sult is not used. In our ex­am­ple, we make sure to com­bine the re­sult in a vari­able to avoid this.
Warmup phase
One-time ini­tial­iza­tions may af­fect neg­a­tively the bench­mark. This is less likely to hap­pen with C code since there is no JIT. None­the­less, you may want to add a small warmup phase.
Too small dataset
If the bench­mark is run­ning us­ing the same in­put pa­ram­e­ters over and over, the in­put data may fit en­tirely in the L1 cache. This af­fects pos­i­tively the bench­mark. There­fore, it is im­por­tant to it­er­ate over a large dataset.
Too reg­u­lar dataset
A reg­u­lar dataset may still af­fect pos­i­tively the bench­mark de­spite its size. While the whole dataset will not fit into L1/L2 cache, the pre­vi­ous run may have loaded most of the data needed for the cur­rent run. In the route lookup ex­am­ple, as route en­tries are or­ga­nized in a tree, it’s im­por­tant to not lin­early scan the ad­dress space. Ad­dress space could be ex­plored ran­domly (a sim­ple lin­ear con­gru­en­tial gen­er­a­tor brings re­pro­ducible ran­domness).
Large over­head
If the bench­marked func­tion runs in a few nanosec­onds, the over­head of the bench­mark in­fra­struc­ture may be too high. Typ­i­cally, the over­head of the method pre­sented here is around 5 nanosec­onds. get_​cycles() is a thin wrap­per around the RDTSC in­struc­tion: it re­turns the num­ber of cy­cles for the cur­rent pro­ces­sor since the last re­set. It’s also vir­tu­al­ized with low over­head in case you run the bench­mark in a vir­tual ma­chine. If you want to mea­sure a func­tion with a greater pre­ci­sion, you need to wrap it in a loop. How­ever, the loop it­self adds to the over­head, no­tably if you need to com­pute a large in­put set (in this case, the in­put can be pre­pared). Com­pil­ers also like to mess with loops. Lastly, a loop hides the re­sult dis­tribution.
Pre­emp­tion
While the bench­mark is run­ning, the thread ex­e­cut­ing it can be pre­empted (or when run­ning in a vir­tual ma­chine, the whole vir­tual ma­chine can be pre­empted by the host). When the func­tion takes less than a mil­lisec­ond to ex­e­cute, one can as­sume pre­emp­tion is rare enough to be fil­tered out by us­ing a per­centile function.
Noise
When run­ning the bench­mark, noise from un­re­lated pro­cesses (or sib­ling hosts when bench­mark­ing in a vir­tual ma­chine) needs to be avoided as it may change from one run to an­other. There­fore, it is not a good idea to bench­mark in a pub­lic cloud. On the other hand, adding con­trolled noise to the bench­mark may lead to less ar­ti­fi­cial re­sults: in our ex­am­ple, route lookup is only a small part of rout­ing a packet and mea­sur­ing it alone in a tight loop af­fects pos­i­tively the benchmark.
Sync­ing par­al­lel bench­marks
While it is pos­si­ble (and safe) to run sev­eral bench­marks in par­al­lel, it may be dif­fi­cult to en­sure they re­ally run in par­al­lel: some in­vo­ca­tions may work in bet­ter con­di­tions be­cause other threads are not run­ning yet, skew­ing the re­sult. Ide­ally, each run should ex­e­cute bo­gus it­er­a­tions and start mea­sures only when all runs are present. This doesn’t seem a triv­ial addition.

As a con­clu­sion, the bench­mark mod­ule pre­sented here is quite prim­i­tive (no­tably com­pared to a frame­work like JMH for Java) but, with care, can de­liver some con­clu­sive re­sults like in these posts: “IPv4 route lookup on Linux” and “IPv6 route lookup on Linux.”

Up­date (2018-01)

In­tel also rec­om­mends dis­abling all power op­ti­miza­tions, no­tably fre­quency scal­ing (cpupower frequency-set -g performance) and turbo mode func­tion­al­i­ties (echo 1 > /​sys/​devices/​system/​cpu/​intel_​pstate/​no_​turbo) as the TSC is in­de­pen­dent of the frequency.

Alternative#

Use of a trac­ing tool is an al­ter­na­tive ap­proach. For ex­am­ple, if we want to bench­mark IPv4 route lookup times, we can use the fol­low­ing process:

while true; do
  ip route get $((RANDOM%100)).$((RANDOM%100)).$((RANDOM%100)).5
  sleep 0.1
done

Then, we in­stru­ment the __fib_​lookup() func­tion with eBPF (through BCC):

$ sudo funclatency-bpfcc __fib_lookup
Tracing 1 functions for "__fib_lookup"... Hit Ctrl-C to end.
^C
     nsecs               : count     distribution
         0 -> 1          : 0        |                    |
         2 -> 3          : 0        |                    |
         4 -> 7          : 0        |                    |
         8 -> 15         : 0        |                    |
        16 -> 31         : 0        |                    |
        32 -> 63         : 0        |                    |
        64 -> 127        : 0        |                    |
       128 -> 255        : 0        |                    |
       256 -> 511        : 3        |*                   |
       512 -> 1023       : 1        |                    |
      1024 -> 2047       : 2        |*                   |
      2048 -> 4095       : 13       |******              |
      4096 -> 8191       : 42       |********************|

Cur­rently, the over­head is quite high, as a route lookup on an empty rout­ing ta­ble is less than 100 ns. Once Linux sup­ports in­ter-event trac­ing, the over­head of this so­lu­tion may be re­duced to be us­able for such mi­crobenchmarks.