UTF-8 validation in x86-64: a scalar reference and an AVX2 version that checks 32 bytes per step. Every build fuzzes one against the other.
AVX2: three nibble tables and a saturating subtractAug 4
1// bench.c: times both validators on 64 MiB of ASCII and 64 MiB of mixed
Benchmark: 64 MiB of ASCII and 64 MiB of mixed textJul 27
2// 1- to 4-byte text, best of five runs each.
3//
4// build/bench.exe
6#include <stdint.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <windows.h>
11int utf8_valid_scalar(const uint8_t *buf, size_t len);
AVX2: three nibble tables and a saturating subtractAug 4
12int utf8_valid_avx2(const uint8_t *buf, size_t len);
14static uint64_t rng = 0x2545F4914F6CDD1Dull;
16static uint32_t next(void)
17{
18 rng ^= rng << 13;
19 rng ^= rng >> 7;
20 rng ^= rng << 17;
21 return (uint32_t)rng;
22}
24// One random code point: half of them ASCII, the rest spread over 2, 3 and 4 bytes.
25static size_t put(uint8_t *p)
26{
27 uint32_t r = next(), c;
28 switch (r % 6) {
29 case 0: case 1: case 2:
30 p[0] = 0x20 + (uint8_t)((r >> 8) % 95);
31 return 1;
32 case 3:
33 c = 0x80 + (r >> 8) % 0x780;
34 p[0] = (uint8_t)(0xC0 | c >> 6);
35 p[1] = (uint8_t)(0x80 | (c & 63));
36 return 2;
37 case 4:
38 c = 0x800 + (r >> 8) % 0xF000;
39 if (c >= 0xD800)
40 c += 0x800;
41 p[0] = (uint8_t)(0xE0 | c >> 12);
42 p[1] = (uint8_t)(0x80 | (c >> 6 & 63));
43 p[2] = (uint8_t)(0x80 | (c & 63));
44 return 3;
45 default:
46 c = 0x10000 + (r >> 8) % 0x100000;
47 p[0] = (uint8_t)(0xF0 | c >> 18);
48 p[1] = (uint8_t)(0x80 | (c >> 12 & 63));
49 p[2] = (uint8_t)(0x80 | (c >> 6 & 63));
50 p[3] = (uint8_t)(0x80 | (c & 63));
51 return 4;
52 }
53}
55static double now(void)
56{
57 LARGE_INTEGER f, c;
58 QueryPerformanceFrequency(&f);
59 QueryPerformanceCounter(&c);
60 return (double)c.QuadPart / (double)f.QuadPart;
61}
63static double best_of_five(int (*fn)(const uint8_t *, size_t), const uint8_t *buf, size_t n)
64{
65 double best = 1e30;
66 for (int i = 0; i < 5; i++) {
67 double t = now();
68 if (!fn(buf, n)) {
69 puts("valid input rejected");
70 exit(1);
71 }
72 t = now() - t;
73 if (t < best)
74 best = t;
75 }
76 return best;
77}
79static void race(const char *name, const uint8_t *buf, size_t n)
80{
81 double scalar = best_of_five(utf8_valid_scalar, buf, n);
AVX2: three nibble tables and a saturating subtractAug 4
82 double avx2 = best_of_five(utf8_valid_avx2, buf, n);
83 printf("%.1f MiB of %s: scalar %.2f GB/s, avx2 %.2f GB/s (%.1fx)\n",
84 n / 1048576.0, name, n / scalar / 1e9, n / avx2 / 1e9, scalar / avx2);
87int main(void)
88{
89 size_t size = (size_t)64 << 20, n = 0;
90 uint8_t *text = malloc(size);
91 if (!text)
92 return 1;
93 for (size_t i = 0; i < size; i++)
94 text[i] = 0x20 + (uint8_t)(next() % 95);
95 race("ASCII", text, size);
96 while (n + 4 <= size)
97 n += put(text + n);
98 race("mixed text", text, n);
99 free(text);
100 return 0;
101}