-
Running time difference
Hi, I have two programs that perform the same task:
Code:
#define N 100000000
int main()
{
long int x;
double sum=0;
char str[100];
for (x=1;x<=N;x++)
sum = sum + x;
sprintf(str,"%.0lf\n",sum);
write(1,str,strlen(str));
exit(0);
}
Code:
#define N 100000000
double sum[N+1];
int main ()
{
long int x;
char str[100];
sum[0]=0;
for (x=1;x<=N;x++)
sum[x] = sum[x-1] + x;
sprintf(str,"%.0lf\n",sum[N]);
write(1,str,strlen(str));
exit(0);
}
In the first one the intermediate additions are being stored in the variable "sum", in the second one every addition is stored in the array. What is the reason behind the second one taking so much longer, if in both cases the value is being stored anyway?
-
5 things here:
1- If you are using libc (sprintf function), why do you choose to write to stdout using write?
2- In your second program,the array is 100 bytes long, but you are trying to access from byte 0 to 99999999?!
3- In your first program sum is of type double (why?).
4- In your programs the iterator x is of type long int (why?).
Isn't it simplier and faster if you do:
Code:
#include <stdio.h>
#define N 1000000000
int main( void )
{
long long sum;
sum = (long long)(N+1)*N / 2; // Arithmetic Series Sum...
printf( "%lld\n", sum );
}
-
Those pieces of code are part of an assignment. I need to work on them later on to optimize them in different ways, however at this point I'd like to understand why the second one takes much longer to run. I know that local variables work in general faster than global ones, but I'd like to know also if there's any other reason involved (like the use of arrays, for instance).
-
Well the OS has to physically map the 400MB of memory you basically use as write-only memory.
That's a lot of memory to write once, read once from.
-