== Check -1 or 0

The most intuitive way would be f, but I came across g in some code base.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include "./tik.h"

static bool b;

void f(int x)
{
b = x == -1 || x == 0;
// cmpl $-1, %edi
// sete %cl
// testl %edi, %edi
// sete %al
// orb %cl, %al

}
void g(int x)
{
b = (unsigned int)x + 1u <= 1u;
// incl %edi
// cmpl $2, %edi
// setb %al
}

int main(int argc, char **argv)
{
int count = (int) (1u << 28);

srand(0);
printf("fast: ");
tik();
for (int i = 0; i < count; ++i) {
g(rand());
}
tik();

srand(0);
printf("slow: ");
tik();
for (int i = 0; i < count; ++i) {
f(rand());
}
tik();

srand(0);
printf("slow: ");
tik();
for (int i = 0; i < count; ++i) {
f(rand());
}
tik();

srand(0);
printf("fast: ");
tik();
for (int i = 0; i < count; ++i) {
g(rand());
}
tik();
(volatile void) b;
return 0;
}

The output on my box:

1
2
3
4
5
$ clang -Ofast test.c && ./a.out
fast: 3.361036
slow: 3.479914
slow: 3.548457
fast: 3.360908