I have enermous array:
int* arr = new int[BIGNUMBER];
How to fullfil it with 1 number really fast. Normally I would do
for(int i = 0; i < BIGNUMBER; i++)
arr[i] = 1
but I think it would take long.
Can I use memcpy
or similar?
I have enermous array:
int* arr = new int[BIGNUMBER];
How to fullfil it with 1 number really fast. Normally I would do
for(int i = 0; i < BIGNUMBER; i++)
arr[i] = 1
but I think it would take long.
Can I use memcpy
or similar?
Under Linux/x86 gcc with optimizations turned on, your code will compile to the following:
Move immediate
int(1)
to rax + rdxIncrement register rdx
Cmp rdi to rdx
If BIGNUMBER has been reached jump back to start.
It takes about 1 second per gigabyte on my machine, but most of that I bet is paging in physical memory to back the uninitialized allocation.
memset(arr, 1, sizeof(int) * BIGNUMBER);
Just unroll the loop by, say, 8 or 16 times. Functions like
memcpy
are fast, but they're really there for convenience, not to be faster than anything you could possibly write:The compiler might be able to unroll the loop for you, but why take the chance?
Some possible alternatives to Andy Prowl's
std::uninitialized_fill_n()
solution, just for posterity:memset
will do the trick.memsetw
, but that's not everywhere.Last but definitely not least, to echo some of the commenters: you should test and see. Compilers tend to be pretty good at recognizing and optimizing patterns like this -- you probably are just trading off portability or readability with anything other than the simple loop or
uninitialized_fill_n
.You may be interested in prior questions:
Try using memset?
http://www.cplusplus.com/reference/cstring/memset/
Use memset or memcpy