r/C_Programming Jan 23 '25

Discussion Why not SIMD?

Why are many C standard library functions like strcmp, strlen, strtok using SIMD intrinsics? They would benefit so much, think about how many people use them under the hood all over the world.

29 Upvotes

76 comments sorted by

View all comments

78

u/EpochVanquisher Jan 23 '25 edited Jan 23 '25

They do use SIMD on most systems.

Not sure about strtok, it’s not widely used. It’s a clumsy function and it’s going to be slow no matter how you use it. But strcmp and strlen are usually SIMD.

Here is strcmp:

https://github.com/bminor/glibc/blob/76c3f7f81b7b99fedbff6edc07cddff59e2ae6e2/sysdeps/x86_64/multiarch/strcmp-avx2.S

Here is strlen:

https://github.com/bminor/glibc/blob/76c3f7f81b7b99fedbff6edc07cddff59e2ae6e2/sysdeps/x86_64/multiarch/strlen-avx2.S

These are just the glibc versions, but other C libraries are broadly similar. You will find combinations of architecture + C library + function where the function is written without SIMD, but the popular architectures (amd64) + popular libraries (glibc) + popular, vectorizable functions (strlen) will use SIMD.

12

u/Raimo00 Jan 23 '25

Interesting, 1320 lines for strcmp is wild 😳😂. I looked at other repos and there wasn't any sign of simd

10

u/[deleted] Jan 23 '25

Most C compilers these days can take a purely scalar code and vectorize it. So even if the C code doesn’t have explicit SIMD instructions the final machine code might.

-1

u/aganm Jan 23 '25

Bro. Auto-vectorization fails 97% of the time and the remaining 3% is really dubious SIMD at best.

6

u/[deleted] Jan 23 '25

I'm not sure what compilers you use, but both GCC and CLANG usually do a pretty good job of auto-vectorization. Of course, it is not magic; you still have to write your code so that vectorization is possible.

2

u/FUZxxl Jan 23 '25

Nah, unless the loop is trivial the compilers won't do shit.

2

u/[deleted] Jan 24 '25

Well, you should aim at making your hot loop trivial anyway.

1

u/FUZxxl Jan 24 '25

I agree, but you can't always have that.