r/cpp • :upvote: • 9h ago

Beating std::memset by 1.2-2.3x or more on runtime lengths of 1–128 bytes

Hey everyone, so it seems as though significant performance gains can be made by decomposing std::memset into a collection of "compile-time known" sizes, when running it with runtime-only known lengths. We bench-marked the code that follows by performing 4096 memsets per iteration into a 64 KiB buffer, with misaligned destination offsets and lengths that are uniformly randomly distributed across [1, N].

Tbh the lengths themselves are sourced from a 64K-entry LCG table, where we vary our starting position on each iteration in order so as to prevent the branch predictor from learning the sequence, and pass the lengths through a volatile to obscure them from the compiler. Both implementations are given a compile-time known fill value of 0x5A.

We're measuring the aggregate number of bytes set per iteration divided by the elapsed time (in MB/s).

For sampling, we start with 60 iterations and repeatedly double the number of iterations per epoch until we reach either our 10-second time limit or our maximum iteration count. We retain the epoch that yielded the lowest total of the relative standard error and the shift in the mean between epochs, with our convergence thresholds being 10% and 5%, respectively.

As far as correctness goes, we're exhaustively testing every length from 0 through 300 across the various destination offsets, verifying both the integrity of the surrounding guard bytes and the equivalence of the resultant buffer contents to those produced by std::memset - let me know what you think about this.

Cheers!

Linux-Clang (EPYC 9V45, AVX-512, Clang 24)

Lengthmemset_decompstd_memsetSpeedupmemset_decomp_up_tostd_memsetSpeedup
1-158,0054,3971.82x9,0454,5142.00x
1-168,4824,7691.78x9,6104,7182.04x
1-179,3874,9491.90x10,1904,9642.05x
1-3116,6298,9181.86x18,1458,9402.03x
1-3217,1829,2211.86x18,7528,9922.09x
1-3317,1419,5261.80x19,0349,4582.01x
1-6333,01917,9821.84x36,42117,9272.03x
1-6432,14216,8801.90x35,42016,3622.16x
1-6531,46715,5482.02x34,65115,0302.31x
1-12716,42511,0271.49x16,28611,2011.45x
1-12816,09811,0671.45x16,93011,4111.48x
1-12917,29611,1091.56x16,67211,0251.51x

Linux-GCC (EPYC 9V45, AVX-512, GCC 16.0.1)

Lengthmemset_decompstd_memsetSpeedupmemset_decomp_up_tostd_memsetSpeedup
1-158,1334,4901.81x8,9584,4332.02x
1-168,4284,6591.81x9,4604,8631.95x
1-178,7384,9011.78x10,1335,0821.99x
1-3116,1178,8381.82x18,0119,0781.98x
1-3216,2768,4731.92x18,7278,3522.24x
1-3316,3249,7751.67x18,8109,2902.02x
1-6330,70618,0421.70x36,22817,6052.06x
1-6431,42816,1361.95x36,38517,0632.13x
1-6528,89115,4741.87x33,92415,6012.17x
1-12715,16611,9361.27x15,57112,0311.29x
1-12815,20911,8791.28x15,83912,5441.26x
1-12914,99212,0661.24x15,36312,5211.23x

Windows-MSVC (Xeon Platinum 8573C, AVX-512, MSVC 19.52)

Lengthmemset_decompstd_memsetSpeedupmemset_decomp_up_tostd_memsetSpeedup
1-153,9886316.32x2,8016324.43x
1-164,3896756.50x3,6726675.51x
1-174,4996786.63x4,5676766.76x
1-317,7201,4035.50x7,8541,3925.64x
1-328,0791,4925.41x6,2481,5094.14x
1-338,2461,4965.51x4,8891,4963.27x
1-6313,3712,2705.89x13,3822,2405.97x
1-6413,5382,4005.64x13,1982,4305.43x
1-6513,6812,4355.62x13,8382,4485.65x
1-1278,8904,2732.08x10,0104,3152.32x
1-1289,0384,2352.13x10,1354,2092.41x
1-1299,1084,4562.04x9,1274,4232.06x

macOS-Clang (Apple M1 virtual, NEON, Clang 23.1.6)

Lengthmemset_decompstd_memsetSpeedupmemset_decomp_up_tostd_memsetSpeedup
1-151,3296911.92x1,4666852.14x
1-161,7217112.42x1,6976122.77x
1-171,6388192.00x1,4577851.86x
1-312,7231,1932.28x2,5861,1372.28x
1-322,1061,2661.66x2,3061,1182.06x
1-332,5421,1902.14x2,3731,2621.88x
1-635,9212,2072.68x5,3161,9782.69x
1-645,9141,9083.10x6,3721,6933.76x
1-655,4532,1792.50x6,3362,2582.81x
1-12711,3674,2542.67x13,0204,9572.63x
1-12812,8554,8352.66x11,7003,0813.80x
1-12911,0694,5862.41x12,8235,1152.51x

macOS-GCC (Apple M1 virtual, NEON, GCC 16.2.0)

Lengthmemset_decompstd_memsetSpeedupmemset_decomp_up_tostd_memsetSpeedup
1-151,3557321.85x1,2967331.77x
1-168747001.25x1,3476692.01x
1-171,6826512.59x1,5917372.16x
1-312,5111,2661.98x2,4961,2631.98x
1-322,3461,1662.01x2,3401,3261.76x
1-332,8461,1652.44x2,2291,1891.88x
1-636,5032,3222.80x5,9212,1892.71x
1-645,5532,3692.34x5,4072,1072.57x
1-655,4042,1652.50x6,1662,2332.76x
1-12713,7625,2432.62x12,8645,2342.46x
1-12813,1425,2992.48x11,8655,2802.25x
1-12911,7384,7222.49x11,5054,6652.47x

Code

#pragma once

#include <cassert>
#include <utility>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <limits>
#include <bit>

#if defined(_MSC_VER) && defined(__AVX512BW__)
	#define MEMSET_DECOMP_MSVC_AVX512BW_IMPLIES_BMI2
#endif

#if defined(__AVX512BW__) && (defined(__BMI2__) || defined(MEMSET_DECOMP_MSVC_AVX512BW_IMPLIES_BMI2))
	#include <immintrin.h>
#endif

#if defined(_MSC_VER) && !defined(__clang__)
	#define MEMSET_DECOMP_INLINE [[msvc::forceinline]] inline
#elif defined(__GNUC__) || defined(__clang__)
	#define MEMSET_DECOMP_INLINE __attribute__((always_inline)) inline
#else
	#define MEMSET_DECOMP_INLINE inline
#endif

namespace memset_decomp_ns {

#if defined(__AVX512F__)
	inline constexpr std::uint64_t register_width{ 64 };
#elif defined(__AVX2__)
	inline constexpr std::uint64_t register_width{ 32 };
#else
	inline constexpr std::uint64_t register_width{ 16 };
#endif

	inline constexpr std::uint64_t small_set_limit{ 16 };
	inline constexpr std::uint64_t smallest_pair_size{ std::bit_floor(small_set_limit + 1) };
	inline constexpr std::uint64_t largest_pair_size{ 128 };

	template<std::uint64_t max_bytes>
	inline constexpr std::uint64_t top_pair_size{ std::bit_floor(max_bytes) < largest_pair_size ? std::bit_floor(max_bytes) : largest_pair_size };

	template<std::uint64_t max_bytes> inline constexpr std::uint64_t pair_class_count{
		top_pair_size<max_bytes> < smallest_pair_size ? 0 : static_cast<std::uint64_t>(std::bit_width(top_pair_size<max_bytes>) - std::bit_width(smallest_pair_size)) + 1
	};

	template<std::byte value, std::uint64_t size> struct pow2_set {
		static_assert(std::has_single_bit(size), "Sorry, but you can only memset a power-of-2 size.");

		MEMSET_DECOMP_INLINE static void impl(std::byte* dst) noexcept {
			std::memset(dst, std::to_integer<int>(value), size);
		}
	};

	template<std::byte value, std::uint64_t pair_size, std::uint64_t chunk_size, typename sequence_type> struct pair_set_impl;

	template<std::byte value, std::uint64_t pair_size, std::uint64_t chunk_size, std::uint64_t... indices>
	struct pair_set_impl<value, pair_size, chunk_size, std::integer_sequence<std::uint64_t, indices...>> {
		MEMSET_DECOMP_INLINE static void impl(std::byte* dst, std::uint64_t byte_count) noexcept {
			std::byte* tail = dst + byte_count - pair_size;
			(pow2_set<value, chunk_size>::impl(dst + indices * chunk_size), ...);
			(pow2_set<value, chunk_size>::impl(tail + indices * chunk_size), ...);
		}
	};

	template<std::byte value, std::uint64_t pair_size> struct pair_set {
		static_assert(std::has_single_bit(pair_size), "Sorry, but pairs must be a power-of-2 size.");
		static constexpr std::uint64_t chunk_size{ pair_size < register_width ? pair_size : register_width };
		static constexpr std::uint64_t chunk_count{ pair_size / chunk_size };

		MEMSET_DECOMP_INLINE static void impl(std::byte* dst, std::uint64_t byte_count) noexcept {
			pair_set_impl<value, pair_size, chunk_size, std::make_integer_sequence<std::uint64_t, chunk_count>>::impl(dst, byte_count);
		}
	};

	template<std::byte value> struct small_set {
		MEMSET_DECOMP_INLINE static void impl(std::byte* dst, std::uint64_t byte_count) noexcept {
			if (byte_count >= 8) {
				pow2_set<value, 8>::impl(dst);
				pow2_set<value, 8>::impl(dst + byte_count - 8);
			} else if (byte_count >= 4) {
				pow2_set<value, 4>::impl(dst);
				pow2_set<value, 4>::impl(dst + byte_count - 4);
			} else if (byte_count >= 2) {
				pow2_set<value, 2>::impl(dst);
				pow2_set<value, 2>::impl(dst + byte_count - 2);
			} else if (byte_count != 0) {
				*dst = value;
			}
		}
	};

	template<std::byte value, typename sequence_type> struct pair_dispatcher;

	template<std::byte value, std::uint64_t... class_indices> struct pair_dispatcher<value, std::integer_sequence<std::uint64_t, class_indices...>> {
		template<std::uint64_t pair_size> MEMSET_DECOMP_INLINE static bool try_pair(std::byte* dst, std::uint64_t byte_count) noexcept {
			if (byte_count <= pair_size * 2) {
				pair_set<value, pair_size>::impl(dst, byte_count);
				return true;
			}
			return false;
		}

		MEMSET_DECOMP_INLINE static void impl(std::byte* dst, std::uint64_t byte_count) noexcept {
			if (byte_count <= small_set_limit) {
				small_set<value>::impl(dst, byte_count);
			} else if (!(try_pair<(smallest_pair_size << class_indices)>(dst, byte_count) || ...)) {
				std::memset(dst, std::to_integer<int>(value), byte_count);
			}
		}
	};

	template<std::byte value, std::uint64_t max_bytes> using memset_dispatcher = pair_dispatcher<value, std::make_integer_sequence<std::uint64_t, pair_class_count<max_bytes>>>;

#if defined(__AVX512BW__) && (defined(__BMI2__) || defined(MEMSET_DECOMP_MSVC_AVX512BW_IMPLIES_BMI2))
	inline constexpr std::uint64_t masked_width{ 64 };

	MEMSET_DECOMP_INLINE __mmask64 length_mask(std::uint64_t byte_count) noexcept {
		return _bzhi_u64(~0ull, static_cast<std::uint32_t>(byte_count));
	}

	template<std::byte value> struct masked_set {
		MEMSET_DECOMP_INLINE static void impl(std::byte* dst, std::uint64_t byte_count) noexcept {
			const __m512i fill{ _mm512_set1_epi8(static_cast<char>(value)) };
			if (byte_count <= masked_width) {
				_mm512_mask_storeu_epi8(dst, length_mask(byte_count), fill);
			} else {
				_mm512_storeu_si512(dst, fill);
				_mm512_mask_storeu_epi8(dst + masked_width, length_mask(byte_count - masked_width), fill);
			}
		}
	};

	template<std::uint64_t max_bytes> MEMSET_DECOMP_INLINE bool fits_masked(std::uint64_t byte_count) noexcept {
		return max_bytes <= masked_width * 2 || byte_count <= masked_width * 2;
	}

	template<std::byte value, std::uint64_t max_bytes> MEMSET_DECOMP_INLINE void memset_decomp_up_to(void* dst, std::uint64_t byte_count) noexcept {
		assert(byte_count <= max_bytes);
		if (fits_masked<max_bytes>(byte_count)) {
			masked_set<value>::impl(static_cast<std::byte*>(dst), byte_count);
		} else {
			memset_dispatcher<value, max_bytes>::impl(static_cast<std::byte*>(dst), byte_count);
		}
	}
#else
	template<std::byte value, std::uint64_t max_bytes> MEMSET_DECOMP_INLINE void memset_decomp_up_to(void* dst, std::uint64_t byte_count) noexcept {
		assert(byte_count <= max_bytes);
		memset_dispatcher<value, max_bytes>::impl(static_cast<std::byte*>(dst), byte_count);
	}
#endif

	template<std::byte value> MEMSET_DECOMP_INLINE void memset_decomp(void* dst, std::uint64_t byte_count) noexcept {
		memset_decomp_up_to<value, std::numeric_limits<std::uint64_t>::max()>(dst, byte_count);
	}

}

#undef MEMSET_DECOMP_MSVC_AVX512BW_IMPLIES_BMI2
#undef MEMSET_DECOMP_INLINE
15 Upvotes

7 comments sorted by

11

u/jk-jeon 7h ago

Did you compare the resulting assembly with std::memset? As far as I understand, doing a similar decomposition by size is how std::memset is implemented from the first place. What do you think is the core difference? Also, did you compare the code size of the functions?

If it's a genuine improvement, how about contributing back to stdlib impls?

4

u/RealTimeChris :upvote: 7h ago

Yep, we did. Here's the Godbolt setup if you want to poke at it yourself (GCC, -O3 -march=x86-64-v4 -DNDEBUG).

You're right that glibc does basically the same size-class decomposition with overlapping head/tail stores. The algorithm isn't the new part. What's different is where it runs and what it knows when it runs:

  1. The fill value is known at compile time. With a runtime size, std::memset(dst, 0, n) compiles to jmp memset, and glibc then has to broadcast an int into a vector register on every call. Here the value is a template parameter, so zero becomes one vpxor, and 0x5a becomes mov imm + vpbroadcastd (or plain immediate stores for the small sizes).
  2. It's inlined, so no call and no ifunc. There's no PLT jump and no ifunc-chosen pointer, and the code sits at the call site, where the compiler can see what's around it.
  3. The size has a known upper bound. memset_decomp_up_to<value, N> only emits the size classes up to N. glibc has to be ready for any size on every call.

The funny part: we also tried telling GCC the bound ourselves (if (n > 64) std::unreachable(); before std::memset). GCC expanded it inline, but it still emitted a 256-byte loop that can never run, plus a 7-step bit-test chain.

Code size (instructions counted by hand from the AVX-512 build):

FunctionInstructions
decomp_up_to<0, 64>~18 (one bzhi mask + one masked vmovdqu8 for 0 to 64 bytes)
decomp<0> (full range, falls back to memset above 256)~30
GCC's own inline memset with the <= 64 hint~60

The honest tradeoff is that this code gets copied into every call site, while glibc keeps a single shared copy. The up_to bound is how you keep that cost small.

As for contributing back: we don't think a libc is the right place, since most of the win comes from things memset(void*, int, size_t) can't express (a compile-time value and a size bound). The more natural target would be the compilers' builtin memset expansion. The unreachable() result above suggests GCC doesn't take advantage of a known bound there yet, and that seems like a reasonable bug report or patch.

3

u/Kriemhilt 7h ago

Why are you specifically optimizing misaligned writes? Is that generally useful, or is it your specific use-case?

2

u/RealTimeChris :upvote: 7h ago edited 7h ago

Because we have no control over the alignment in the cases we encounter, in our usage of the function, which is in our json library.

•

u/Kriemhilt 3h ago

Oh you're just writing bytes, so they're not so much misaligned as just not cache-aligned. Ok.

Second question, did you compare std::fill or std::ranges::fill? Those should also be inlined, and the const fill value can propagate in...

•

u/RealTimeChris :upvote: 2h ago

No but that is a fantastic idea, I will probably do that - thanks!

•

u/c0d3c 3h ago

It reminds me of the good old days of optimizing unaligned fills and copies in hand-rolled x86 assembler. That would have been compile time, in a fashion :-)

IIRC I did something more recently maybe 15 years ago with inline asm and found gains vs memcpy - which surprised me, of course GCC has come a long way since, but general purpose always has a cost.