Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time taken for memcpy decreases after certain point

Tags:

c

malloc

memcpy

I ve a code which increases the size of the memory(identified by a pointer) exponentially.
Instead of realloc(), I use malloc() followed by memcpy()...

int size=5,newsize;
int *c = malloc(size*sizeof(int));
int *temp;

while(1)
{
   newsize=2*size;
   //begin time
   temp=malloc(newsize*sizeof(int));
   memcpy(temp,c,size*sizeof(int));
   //end time
   //print time in mili seconds
   c=temp;
   size=newsize;
}

Thus the number of bytes getting copied is increasing exponentially.

The time required for this task also increases almost linearly with the increase in size. However after certain point, the time taken abruptly reduces to a very small value and then remains constant.

I recorded time for similar code, copying data of my own type.

5 -> 10  - 2 ms  
10 -> 20  - 2 ms  
.  
.  
2560 -> 5120 - 5 ms  
.  
.  
20480 -> 40960 - 30 ms  
40960 -> 91920 - 58 ms  
367680 -> 735360 - 2 ms  
735360 -> 1470720 - 2 ms  
1470720 -> 2941440 - 2 ms

What is the reason for this drop in time ? Does a more optimal memcpy method get called when the size is large ?

like image 639
tss Avatar asked Feb 20 '23 23:02

tss


2 Answers

Since your code doesn't do free() on the old memory block, make sure that the new allocations simply don't start to fail. It could be that memcpy() errors out when given a NULL pointer, thus completing very quickly.

like image 50
unwind Avatar answered Mar 04 '23 15:03

unwind


Have you checked return values of malloc?

I think it just fails after a certain point.

like image 39
Alexander Pogrebnyak Avatar answered Mar 04 '23 15:03

Alexander Pogrebnyak