3 ms·
This reminds me of when I made a program faster by adding a print statement to it. I am not able to find the program but I was able to create a new one as simil
by robalni 6y ago
This reminds me of when I made a program faster by adding a print statement to it.
I am not able to find the program but I was able to create a new one as similar to it as I remember and it seems that this weird trick works in this program too.
When I uncomment the puts("hi") line in the code below, the time it takes to run the program consistently changes from 5.6 to 5.4 seconds on my machine if I compile without optimizations.
#include <stdio.h>
int main() {
long tri_side = 1;
long tri_area = 1;
long sq_side = 1;
long sq_area = 1;
while (sq_side < 1000000000) {
if (sq_area == tri_area) {
printf("tri:%ld sq:%ld area:%ld\n", tri_side, sq_side, sq_area);
//puts("hi");
}
if (sq_area < tri_area) {
sq_area += sq_side * 2 + 1;
sq_side += 1;
} else {
tri_area += tri_side + 1;
tri_side += 1;
}
}
}
- guerrilla 6y agoI wasn't able to reproduce this but I'm wondering if it could have to do with buffer flushing. puts may implicitly do whatever fflush(stdio) does. [1] [1]. https://linux.die.net/man/3/fflush https://linux.die.net/man/3/fflush