Skip to content

Instantly share code, notes, and snippets.

@evincarofautumn
Created December 5, 2014 22:15
Show Gist options
  • Save evincarofautumn/976a430685e3fa0b9516 to your computer and use it in GitHub Desktop.
Save evincarofautumn/976a430685e3fa0b9516 to your computer and use it in GitHub Desktop.
Clang Optimisation Bug
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int sum(int a, int b, int c, int d) {
return a + b + c + d;
}
int product(int a, int b, int c, int d) {
return a * b * c * d;
}
int expression(int x) {
return (x ? sum : product)(1, 2, 3, 4);
}
int statement(int x) {
if (x)
return sum(1, 2, 3, 4);
else
return product(1, 2, 3, 4);
}
int main() {
int i;
struct timeval
start_expression,
end_expression,
start_statement,
end_statement;
double
elapsed_expression,
elapsed_statement;
int x = 0;
const int samples = 10000000;
srand(time(NULL));
gettimeofday(&start_expression, NULL);
for (i = 0; i < samples; ++i)
x += expression(rand() & 1);
gettimeofday(&end_expression, NULL);
printf("%d\n", x);
x = 0;
gettimeofday(&start_statement, NULL);
for (i = 0; i < samples; ++i)
x += statement(rand() & 1);
gettimeofday(&end_statement, NULL);
printf("%d\n", x);
elapsed_statement
= (double)end_statement.tv_sec
+ (double)end_statement.tv_usec * 1e-6
- (double)start_statement.tv_sec
- (double)start_statement.tv_usec * 1e-6;
elapsed_expression
= (double)end_expression.tv_sec
+ (double)end_expression.tv_usec * 1e-6
- (double)start_expression.tv_sec
- (double)start_expression.tv_usec * 1e-6;
printf(
"expression: %.2f\n"
"statement: %.2f\n"
"expression is %.2f%% slower than statement\n",
elapsed_statement,
elapsed_expression,
100 * (elapsed_expression - elapsed_statement) / elapsed_statement
);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment