5 ms·
The toy example for those curious: #include <stdio.h> int main(void) { int i; int a[2000] ; for(i = 0; i < 2000; i++){ a[i] = i ; } printf("
by naveen99 3y ago
The toy example for those curious:
#include <stdio.h>
int main(void) {
int i;
int a[2000] ;
for(i = 0; i < 2000; i++){
a[i] = i ;
}
printf("%d\n", a[5]);
}
This program initializes an array `a` of size 2000, populates it with integers from 0 to 1999, and then prints the value at index 5, which is 5.
Just as with the Python program, we can optimize this program significantly. Given that we're only interested in the sixth element (index 5) of the array, we don't need to construct and populate the entire array.
Here's an optimized version of the code:
#include <stdio.h>
int main(void) {
printf("%d\n", 5);
}
- naveen99 3y agoBut when I tried to get it to remove the dependency on studio.h, it said that’s too hard. Might have gone further with a more reasonable request I guess. Also not necessary as gcc does that anyway.
- Izkata 3y agoCode indentation is 2 spaces on here, you have to do it to all the lines you want formatted that way. That's why the first one got a bunch of lines combined, it treated them as one paragraph instead of code.
- naveen99 3y agothanks. fixed.
- cypress66 3y agoPrintf is horribly slow compared to puts
- jmgao 3y agoputs isn't applicable here because you actually need to format the %d, but any compiler worth using (i.e. not MSVC: https://gcc.godbolt.org/z/zx74vY1za https://gcc.godbolt.org/z/zx74vY1za) will optimize a printf of a constant string ending in a newline into a puts.
- cypress66 3y agoNo you don't need to format the %d. The same way you collapsed the loop into the constant 5, you collapse that printf into puts("5\n")