Created
January 6, 2023 05:11
-
-
Save dpzmick/607bdda8a518f77f4dee1cacbc7c4903 to your computer and use it in GitHub Desktop.
This file contains 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 <stdbool.h> | |
#include <stddef.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <time.h> | |
#if defined(__x86_64__) | |
// fakes a read+write to register | |
// using 'r' means that the value will be placed into a _general_ register for | |
// the read if it not already in one, then possible re-read into another | |
// non-general registers that depend on it afterwards (due the the "write") | |
#define compiler_forget(p) asm ("# compiler_forget(" #p "[%0])@" : "+r"(p) : : ) | |
// volatile version to prevent optimizing it out | |
#define compiler_forget_v(p) asm volatile ("# compiler_forget_v(" #p "[%0])@" : "+r"(p) : : ) | |
#elif defined(__aarch64__) | |
// clang doesn't like my square brace printing comments | |
#define compiler_forget(p) asm ("# compiler_forget(" #p ")@" : "+r"(p) : : ) | |
#define compiler_forget_v(p) asm volatile ("# compiler_forget_v(" #p ")@" : "+r"(p) : : ) | |
#else | |
#error "unsupported architecture" | |
#endif | |
bool rounds_to_nearest_volatile() { | |
static volatile float fmin = 1e-38; | |
return (fmin + 1.0f == 1.0f - fmin); | |
} | |
bool rounds_to_nearest_forget() { | |
float fmin = 1e-38; | |
compiler_forget(fmin); | |
return (fmin + 1.0f == 1.0f - fmin); | |
} | |
int64_t now(void) { | |
struct timespec t[1]; | |
clock_gettime(CLOCK_REALTIME, t); | |
return t->tv_sec * 1000000000 + t->tv_nsec; | |
} | |
int main() { | |
for (size_t i = 0; i < 4; ++i) { | |
{ | |
int64_t st = now(); | |
for (size_t i = 0; i < 500000; ++i) { | |
bool r = rounds_to_nearest_volatile(); | |
compiler_forget_v(r); | |
} | |
int64_t ed = now(); | |
printf("v %lld\n", ed-st); | |
} | |
{ | |
int64_t st = now(); | |
for (size_t i = 0; i < 500000; ++i) { | |
bool r = rounds_to_nearest_forget(); | |
compiler_forget_v(r); | |
} | |
int64_t ed = now(); | |
printf("f %lld\n", ed-st); | |
} | |
} | |
printf("done!\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment