Last active
May 19, 2022 18:58
-
-
Save m1lkweed/55ffaa0bd99d9399609c409972812d04 to your computer and use it in GitHub Desktop.
Evaluate a body of code and return its size
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
// Works in GCC and clang, produces correct results at all optimization levels | |
// returns the contents of the instruction pointer | |
#define get_pc() ({ \ | |
register void *temp; \ | |
asm volatile("call .+5\n\t" \ | |
"pop %0" \ | |
:"=r"(temp) \ | |
); \ | |
temp; \ | |
}) | |
// returns the size of a block of code | |
#ifdef __OPTIMIZE__ | |
#define ASM_SIZEOF_OVERHEAD 6 | |
#else | |
#define ASM_SIZEOF_OVERHEAD 16 | |
#endif | |
#define asm_sizeof(body) ({ \ | |
void *_asm_sizeof_first = get_pc(); \ | |
body; \ | |
void *_asm_sizeof_second = get_pc(); \ | |
(size_t)(_asm_sizeof_second - (_asm_sizeof_first + ASM_SIZEOF_OVERHEAD)); \ | |
}) | |
int main(){ | |
printf("%zu\n", asm_sizeof(puts("Hello, World!"))); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment