Related C++ Core guidelines
- ES.100: Don’t mix signed and unsigned arithmetic
- ES.101: Use unsigned types for bit manipulation
- ES.102: Use signed types for arithmetic
Operations note
- ADD - 1 cycle
- IMUL - 3 cycles
- DIV - at least 20 times slower then IMUL
Code samples
uint64_t arc_unsigned(uint64_t n) {
uint64_t sum = 0;
for(uint64_t i = 1; i <=n; i++) {
sum += i;
}
return sum;
}
int64_t arc_signed(int64_t n) {
int64_t sum = 0;
for(int64_t i = 1; i <=n; i++) {
sum += i;
}
return sum;
}
- Undefined behavior in signed utilized in performance improvement in clang-12 …
- … and no effect in clang-17
Recommendations
- Use warning flags
-Wall
,-Wextra
,-pedantic
,-Werror
- Use newer compilers - they optimize better!
- Use sanitizers -
-fsanitize=signed-integer-oveflow
,-fsanitize=unsigned-integer-oveflow
- Use special types for better performance -
int_fastN_t
,uint_fastN_t
- Know your CPU
- Use special helpers from the standard - MAKE_SIGNED, MAKE_UNSIGNED
- Use C++20 safe comparators
- Avoid using auto when not sure about the type
- Use concrete types when possible!
- Use modern loops as much as you can (instead of indexed ones)
- Use strong types