Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Quick and dirty trap on overflow overhead check
#include <stdio.h>
#include <time.h>
#include <stdint.h>
__asm(
".align 16\n"
"_overhead:\n"
"mov 4(%esp), %eax\n"
"mov $25, %ecx\n"
"1: dec %ecx\n"
"jnz 1b\n"
"ret\n"
".align 16\n"
"_add_c:\n"
"mov 4(%esp), %eax\n"
"mov $25, %ecx\n"
"1: mull 8(%esp)\n"
"jc Ltrap\n"
"add $1, %eax\n"
"jc Ltrap\n"
"dec %ecx\n"
"jnz 1b\n"
"ret\n"
"Ltrap: jmp _abort\n"
".align 16\n"
"_add_u:\n"
"mov 4(%esp), %eax\n"
"mov $25, %ecx\n"
"1: mull 8(%esp)\n"
"add $1, %eax\n"
"dec %ecx\n"
"jnz 1b\n"
"ret\n"
);
extern void overhead(unsigned,unsigned);
extern void add_c(unsigned,unsigned);
extern void add_u(unsigned,unsigned);
#define ITERATIONS 100000000
static inline uint64_t rdtscp(void)
{
uint64_t v;
__asm volatile("rdtscp" : "=A" (v));
return v;
}
int main()
{
uint64_t start, end_overhead, end_c, end_u;
// Multiple iters to eliminate cache effects
for(int j = 0; j < 5; j++) {
putc('.', stdout);
start = rdtscp();
for(uintmax_t i = 0; i < ITERATIONS; i++) {
overhead(4, 1);
}
end_overhead = rdtscp();
for(uintmax_t i = 0; i < ITERATIONS; i++) {
add_c(4, 1);
}
end_c = rdtscp();
for(uintmax_t i = 0; i < ITERATIONS; i++) {
add_u(4, 1);
}
end_u = rdtscp();
if(j < 2) continue;
printf("Overhead: %jd, Checked: %jd, Unchecked: %jd\n",
(uintmax_t)(end_overhead - start),
(uintmax_t)(end_c - end_overhead),
(uintmax_t)(end_u - end_c));
uintmax_t overhead_t = end_overhead - start;
uintmax_t real_c = (end_c - end_overhead) - overhead_t;
uintmax_t real_u = (end_u - end_c) - overhead_t;
printf("Computtion times: Checked: %jd, Unchecked: %jd\n", real_c, real_u);
double slowdown = 1 - ((double)real_u)/((double)real_c);
printf("Slowdown: %f%%\n", slowdown * 100);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment