yo3hcv
yo3hcv

Reputation: 1669

C, Fast way to limit a number to <= 64

Which is the fastest way to limit a number to 64 inclusive (ie. <= 64)

len = len > 64 ? 64 : len; /* limit to 64 */

Thanks!

Upvotes: 0

Views: 108

Answers (2)

I created a program

#include <stdio.h>

int main(void) {
    unsigned int len;
    scanf("%u", &len);
    len = len > 64 ? 64 : len;
    printf("%u\n", len);
}

and compiled with gcc -O3 and it generated this assembly:

cmpl    $64, 4(%rsp)
movl    $64, %edx
leaq    .LC1(%rip), %rsi
cmovbe  4(%rsp), %edx

the leaq there loads the "%u\n" string in between - I presume it is because the timing of the instructions. The generated code seems pretty efficient. There are no jumps, just a conditional move. No branch prediction failure.

So the best way to optimize your executable is to get a good compiler.

Upvotes: 3

Don't bother. The compiler optimizes better than you could.

You might perhaps try

len = ((len - 1) & 0x3f) + 1;

(but when len is 0 -or 65, etc...- this might not give what you want)

If that is so important for you, benchmark!

Upvotes: 3

Related Questions