Skip to content

Instantly share code, notes, and snippets.

@m1lkweed
Last active May 19, 2022 18:58
Show Gist options
  • Save m1lkweed/55ffaa0bd99d9399609c409972812d04 to your computer and use it in GitHub Desktop.
Save m1lkweed/55ffaa0bd99d9399609c409972812d04 to your computer and use it in GitHub Desktop.
Evaluate a body of code and return its size
// 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