Skip to content

Instantly share code, notes, and snippets.

@mb64
Created October 17, 2020 23:59
Show Gist options
  • Save mb64/0088f871d70b3aaddf79efc35aa9fd9f to your computer and use it in GitHub Desktop.
Save mb64/0088f871d70b3aaddf79efc35aa9fd9f to your computer and use it in GitHub Desktop.
GCC vs repne scasl: wstrlen bench
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
extern size_t wstrlen_c(unsigned int *);
extern size_t wstrlen_asm(unsigned int *);
int main() {
unsigned int *data = malloc(1001 * sizeof(int));
memset(data, 'h', 1000 * sizeof(int));
data[1000] = 0;
size_t l = WSTRLEN(data);
if (l != 1000)
printf("bad: wanted 1000, got %lu\n", l);
size_t sum = 0;
for (int i = 0; i < 1000000; i++)
sum += WSTRLEN(data);
return sum;
}
.PHONY: all bench
all: bench
bench: main_c main_asm
@echo "Running the C version..."
@bash -c 'time ./main_c'
@echo
@echo "Running the asm version..."
@bash -c 'time ./main_asm'
wstrlen_c.o: wstrlen_c.c
gcc -O3 -c wstrlen_c.c
wstrlen_asm.o: wstrlen_asm.s
gcc -O3 -c wstrlen_asm.s
main_c: wstrlen_c.o main.c
gcc -Wall -O3 -DWSTRLEN=wstrlen_c main.c wstrlen_c.o -o main_c
main_asm: wstrlen_asm.o main.c
gcc -Wall -O3 -DWSTRLEN=wstrlen_asm main.c wstrlen_asm.o -o main_asm
Running the C version...
real 0m0.250s
user 0m0.250s
sys 0m0.000s
Running the asm version...
real 0m0.505s
user 0m0.504s
sys 0m0.000s
.text
.globl wstrlen_asm
wstrlen_asm:
xor %eax, %eax
xor %ecx, %ecx
dec %rcx
mov %ax, %es
cld
repne scasl
not %ecx
dec %ecx
mov %ecx, %eax
ret
#include <stddef.h>
size_t wstrlen_c(unsigned int *str) {
size_t len = 0;
while (str[len])
len++;
return len;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment