Skip to content
Prev 36537 / 63421 Next

suggestion how to use memcpy in duplicate.c

Follow up...
Herv? Pag?s wrote:
So for copying a vector of integer (with recycling of the source),
yes, a memcpy-based implementation is much faster, for long and small
vectors (even for a length 3 vector being recycled 3.3 million
times ;-) ), at least on my system:

nt = 3; ns = 10000000; kmax = 100; copy_ints:

   real	0m1.206s
   user	0m1.168s
   sys	0m0.040s

nt = 3; ns = 10000000; kmax = 100; copy_ints2:

   real	0m6.326s
   user	0m6.264s
   sys	0m0.052s


Code:
=======================================================================
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void memcpy_with_recycling_of_src(char *dest, size_t dest_nblocks,
				  const char *src, size_t src_nblocks,
				  size_t blocksize)
{
	int i, imax, q;
	size_t src_size;

	imax = dest_nblocks - src_nblocks;
	src_size = src_nblocks * blocksize;
	for (i = 0; i <= imax; i += src_nblocks) {
		memcpy(dest, src, src_size);
		dest += src_size;
		i += src_nblocks;
	}
	q = dest_nblocks - i;
	if (q > 0)
		memcpy(dest, src, q * blocksize);
	return;
}

void copy_ints(int *dest, int dest_length,
                const int *src, int src_length)
{
	memcpy_with_recycling_of_src((char *) dest, dest_length,
				     (char *) src, src_length,
				     sizeof(int));
}

/* the copyVector() way */
void copy_ints2(int *dest, int dest_length,
                 const int *src, int src_length)
{
	int i;

	for (i = 0; i < dest_length; i++)
		dest[i] = src[i % src_length];
}

int main()
{
	int nt, ns, kmax, k;
	int *t, *s;

	nt = 3;
	ns = 10000000;
	kmax = 100;
	t = (int *) malloc(nt * sizeof(int));
	s = (int *) malloc(ns * sizeof(int));
	for (k = 0; k < kmax; k++)
		//copy_ints(s, ns, t, nt);
		copy_ints2(s, ns, t, nt);
	return 0;
}

Note that the function that actually does the job is
memcpy_with_recycling_of_src(). It can be reused for copying
vectors with elements of an arbitrary size.

Cheers,
H.