Btw, i know the pointer loop can be optimized, i just wanted to compare them side by side. When you increment the pointer, you get a slight performance increase over array indexing. However, the gap between those is not as big as the gap between indexing and straight arithmetic.
Can anybody Explain why this is?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct
{
double array;
double pointer;
}TIMECOUNT;
TIMECOUNT timeap = {0,0};
time_t start;
time_t stop;
double temp;
char array1[2000000];
int counter;
int i;
int main(void)
{
char* p = array1;
for(i=0;i<2000000;i++)
{
array1[i]=0;
}
start = clock();
for(i = 0; i < 2000000; i++)
{
array1[i] = 65;
array1[i] *= 20000;
array1[i] = 20;
array1[i] = array1[i]*array1[i];
//putchar(array1[i]);
}
stop = clock();
temp = ((double )(stop - start))/((double )CLOCKS_PER_SEC);
//printf("%f seconds array\n", temp);
timeap.array+=temp;
for(i=0;i<2000000;i++)
{
array1[i]=0;
}
start = clock();
for(i = 0; i < 2000000; i++)
{
*(p+i) = 65;
*(p+i) *= 20000;
*(p+i) = 20;
*(p+i) = *(p + i) * *(p + i);
}
stop = clock();
temp = ((double )(stop - start))/((double )CLOCKS_PER_SEC);
//printf("%f seconds array\n", temp);
timeap.pointer+=temp;
counter++;
if (counter%100==0){
printf("\aMILESTONE\n");
printf("-------------------------------------\n");
printf("TotalTimes, Array = %.3lf, Pointer = %.3lf\n\n\n", timeap.array, timeap.pointer);
if(counter==100000){
system("pause");
return 0;
}
}
main();
}
When I say it can be optimized, i mean such as:
for(; p <= q; p++)
{
*p = 65;
*p *= 20000;
*p = 20;
*p = *p * *p;
}
Where q is the last element in the array.
Sorry for my sloppy coding, i just did it really quick b/c i was curious.


Sign In
Create Account


Back to top










