Skip to content

Instantly share code, notes, and snippets.

@CandyMi
Last active December 29, 2022 08:06
Show Gist options
  • Save CandyMi/15863f7284c14e218b1009ce9c5ab5e8 to your computer and use it in GitHub Desktop.
Save CandyMi/15863f7284c14e218b1009ce9c5ab5e8 to your computer and use it in GitHub Desktop.
基于 intel sse4指令集的crc32c实现
#include <stdint.h>
#if defined(__x86_64__) || defined(__i386__)
static inline uint32_t _mm_crc32_u8(uint32_t crc, uint8_t v) {
__asm__ volatile("crc32b %1, %0" : "+r"(crc) : "rm"(v));
return crc;
}
static inline uint32_t _mm_crc32_u16(uint32_t crc, uint16_t v) {
__asm__ volatile("crc32w %1, %0" : "+r"(crc) : "rm"(v));
return crc;
}
static inline uint32_t _mm_crc32_u32(uint32_t crc, uint32_t v) {
__asm__ volatile("crc32l %1, %0" : "+r"(crc) : "rm"(v));
return crc;
}
static inline uint32_t _mm_crc32_u64(uint32_t crc, uint64_t v) {
uint64_t result = crc;
__asm__ volatile("crc32q %1, %0" : "+r"(result) : "rm"(v));
return result;
}
#elif defined (__arm__) || defined (__aarch64__)
static inline uint32_t _mm_crc32_u8(uint32_t crc, uint8_t v) {
__asm__ volatile("crc32cb %w[c], %w[c], %w[v]":[c]"+r"(crc):[v]"r"(v));
return crc;
}
static inline uint32_t _mm_crc32_u16(uint32_t crc, uint16_t v) {
__asm__ volatile("crc32ch %w[c], %w[c], %w[v]":[c]"+r"(crc):[v]"r"(v));
return crc;
}
static inline uint32_t _mm_crc32_u32(uint32_t crc, uint32_t v) {
__asm__ volatile("crc32cw %w[c], %w[c], %w[v]":[c]"+r"(crc):[v]"r"(v));
return crc;
}
static inline uint32_t _mm_crc32_u64(uint32_t crc, uint64_t v) {
uint64_t result = crc;
__asm__ volatile("crc32cx %w[c], %w[c], %x[v]":[c]"+r"(result):[v]"r"(v));
return result;
}
#else
#error "Unsupported platforms"
#endif
static inline unsigned int luaS_hash (const char *str, size_t l, unsigned int seed) {
unsigned int hash = seed ^ cast_uint(l);
while (l >= 8)
{
hash = _mm_crc32_u64(hash, *(uint64_t*)str);
str += 8; l -= 8;
}
while (l >= 4)
{
hash = _mm_crc32_u32(hash, *(uint32_t*)str);
str += 4; l -= 4;
}
while (l >= 2)
{
hash = _mm_crc32_u16(hash, *(uint16_t*)str);
str += 2; l -= 2;
}
while (l--)
hash = _mm_crc32_u8(hash, *(uint8_t*)str++);
return hash;
}
local mrandom = math.random
local tconcat = table.concat
local str = "administratoradministrator"
local a, b = 1 << 32, 1 << 60
for i = 1, 1000000 do
-- local v = str .. mrandom(a, b) .. str .. mrandom(a, b) .. str .. mrandom(a, b)
local v = tconcat { str , mrandom(a, b) , str , mrandom(a, b) , str , mrandom(a, b)}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment