Skip to content

Instantly share code, notes, and snippets.

@WiwilZ
Last active April 16, 2024 10:45
Show Gist options
  • Select an option

  • Save WiwilZ/dc6a608f5ac3ff797a570577d26430b6 to your computer and use it in GitHub Desktop.

Select an option

Save WiwilZ/dc6a608f5ac3ff797a570577d26430b6 to your computer and use it in GitHub Desktop.
DoNotOptimize function
#if defined(_MSC_VER) && !defined(__clang__)
namespace detail {
#pragma optimize("", off)
void DoNotOptimizeImpl(const void*) noexcept {}
#pragma optimize("", on)
}
[[msvc::forceinline]] void DoNotOptimize(const auto& x) noexcept {
Detail::DoNotOptimizeImpl(&x);
}
#else
#include <type_traits>
namespace detail {
template <typename T>
concept InRegister = std::is_trivially_copyable_v<T> && sizeof(T) <= sizeof(T*) && !std::is_pointer_v<T>;
template <typename T>
concept InMemory = !InRegister<T>;
}
[[gnu::always_inline]] void DoNotOptimize(const detail::InRegister auto& x) noexcept {
asm volatile("" : : "r"(x));
}
[[gnu::always_inline]] void DoNotOptimize(const detail::InMemory auto& x) noexcept {
asm volatile("" : : "m"(x) : "memory");
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment