Skip to content

Instantly share code, notes, and snippets.

@temoto
Last active December 12, 2015 05:28
Show Gist options
  • Save temoto/4722289 to your computer and use it in GitHub Desktop.
Save temoto/4722289 to your computer and use it in GitHub Desktop.
Benchmark IMULQ against SHL on x86-64
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/*
Compile with:
gcc -g -O0 -Wall -Werror
*/
static int64_t mul_imul(int64_t n) {
asm __volatile__ (
"movq %1, %%rax\n\t"
"imulq $8, %%rax\n\t"
"movq %%rax, %0\n\t"
"\n"
:"=r"(n)
:"r"(n)
:"%rax"
);
return n;
}
static int64_t mul_shl(int64_t n) {
asm __volatile__ (
"movq %1, %%rax\n\t"
"shl $3, %%rax\n\t"
"movq %%rax, %0\n\t"
"\n"
:"=r"(n)
:"r"(n)
:"%rax"
);
return n;
}
void test(int64_t n) {
printf("Testing %ld\n", n);
int64_t expected = n * 8;
int64_t result_imul = mul_imul(n);
int64_t result_shl = mul_shl(n);
if (result_imul != expected) {
printf("error: imul: expected: %ld got: %ld\n", expected, result_imul);
exit(1);
}
if (result_shl != expected) {
printf("error: shl: expected: %ld got: %ld\n", expected, result_shl);
exit(1);
}
}
int main(void) {
int64_t i = 0;
for (i = -260; i < 17000; i++) {
test(i);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment