Last active
February 27, 2020 15:25
-
-
Save madmann91/9898c18d17fdf96e16e15c9f0d75f126 to your computer and use it in GitHub Desktop.
Fast, vectorized morton code encoding. Completely portable and only relies on compiler optimizations.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdint.h> | |
| #include <inttypes.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| static inline uint64_t split(uint64_t x, int log_bits) { | |
| uint64_t mask = (UINT64_C(1) << (1 << log_bits)) - 1; | |
| for (int i = log_bits, n = 1 << log_bits; i > 0; --i, n >>= 1) { | |
| mask = (mask | (mask << n)) & ~(mask << (n / 2)); | |
| x = (x | (x << n)) & mask; | |
| } | |
| return x; | |
| } | |
| uint64_t encode(uint64_t x, uint64_t y, uint64_t z, int log_bits) { | |
| return split(x, log_bits) | (split(y, log_bits) << 1) | (split(z, log_bits) << 2); | |
| } | |
| int main(int argc, char** argv) { | |
| size_t n_iters = 500; | |
| uint64_t res = 0; | |
| for (size_t iter = 0; iter < n_iters; ++iter) { | |
| for (uint64_t i = 0; i < 256 * 256 * 256; ++i) | |
| res += encode(i & 0xFF, (i >> 8) & 0xFF, (i >> 16) & 0xFF, 5); | |
| } | |
| printf("%"PRIu64"\n", res); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment