memset function vs. for loop – Fast method to allocate memory by default value

When you want to craete an array in C/C++ assigned by the default value the best solution will be the memset function. Examine this listing of the C code:

#include <sys/time.h>
#include <stdio.h>
#include <string.h> /* memset */
#include <unistd.h> /* close */
#include <stdlib.h>

void CasualFor(int times, int value);
void UseMemSet(int times, int value);

int main(int argc, char ** argv)
{
struct timeval start, end;

long mtime, seconds, useconds;

gettimeofday(&start, NULL);
//CasualFor(100000, 0);
UseMemSet(100000, 0);
gettimeofday(&end, NULL);

seconds = end.tv_sec – start.tv_sec;
useconds = end.tv_usec – start.tv_usec;

mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

printf(“Elapsed time: %ld milliseconds\n”, mtime);

return 0;
}

void CasualFor(int times, int value)
{
int i;
int j;
for(i=0; i < times; i++)
{
int * tab = malloc(1000 * sizeof(int));
for(j=0; j < 1000; j++) tab[j] = value;
free(tab);
}

}

void UseMemSet(int times, int value)
{
int i;
for(i=0;i<times;i++)
{
int * tab = malloc(1000 * sizeof(int));
memset(tab, value, 1000 * sizeof(int));

free(tab);
}
}

Take care about these two calling of functions:

//CasualFor(100000, 0);
UseMemSet(100000, 0);

First one is commented becase I want obtain time of them execution separately, and there is the result:

CasualFor(100000, 0):   Elapsed time: 374 milliseconds
UseMemSet(100000, 0):   Elapsed time: 27 milliseconds

So now you are convinced how quick is memset? I am.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s