double d[10];
int length = 10;
memset(d, length * sizeof(double), 0);
//or
for (int i = length; i--;)
d[i] = 0.0;
17 Answers
If you really care you should try and measure. However the most portable way is using std::fill():
std::fill( array, array + numberOfElements, 0.0 );
-
10IMO the perfect answer. If
std::memset()
is possible, I would expect the std lib implementation to call this, if not, it does the right thing, too.– sbiSep 3, 2009 at 13:26 -
13Did you guys see this is A C question and NOT C++. AFAIK, C doesn't have fill function, much less std namespace– vehomzzzSep 3, 2009 at 14:23
-
10I swear it was tagged
c++
when it was first published! (not that I would preferc++
way here). Sep 3, 2009 at 15:04 -
18@hacker: Enigma retagged it as a C question about 1 minute before complaining about this answer. Which is fine, though his comment strikes me as unjustly aggressive, when you take this into account.– BrianSep 3, 2009 at 15:08
-
16So I guess the answer to the question "did you guys see this is a C question", is "no, obviously not, because it was a C++ question". Am tempted to change the question to setting a Java array of doubles to 12.4, then complain that all the answers are irrelevant ;-) Sep 3, 2009 at 16:13
Note that for memset you have to pass the number of bytes, not the number of elements because this is an old C function:
memset(d, 0, sizeof(double)*length);
memset can be faster since it is written in assembler, whereas std::fill
is a template function which simply does a loop internally.
But for type safety and more readable code I would recommend std::fill()
- it is the c++ way of doing things, and consider memset
if a performance optimization is needed at this place in the code.
-
27Sorry, there are plenty of implementations that specialize std::fill and std::copy for POD. And because these specializations can assume aligned pointers, they'll likely be faster than std::memset(). Memset has to deal with all edge cases.– MSaltersSep 4, 2009 at 10:52
-
1+1 for std:fill(), this is the C++ way, unless a real need in performance is needed. Dec 5, 2012 at 10:39
-
6@StephaneRolland at least in GCC with
-O2
std∷fill
is faster. You can check it for yourself by asking the compiler generate an assembly with-S
option — you'd see thatmemset
turn's out to be a call to a library function, whilststd∷fill
becomes just a few assembly instructions without acall
at all.– Hi-AngelJun 9, 2015 at 8:26 -
2@Hi-Angel: As I commented on the OP, depending on compile options, constant-size
memset
is inlined torep stosq
, which will perform very well (Probably better than the loop you get fromstd::fill
, except for very small arrays because it has a little bit of startup overhead). Mar 13, 2016 at 10:02 -
1@AtulVaibhav: "Plain Old Data". Roughly means "a struct like you'd have in C". The exact meaning depends a bit on the C++ standard version (this question predates C++11), but it definitely means that the type has no user-defined constructor.– MSaltersFeb 11, 2021 at 16:36
Try this, if only to be cool xD
{
double *to = d;
int n=(length+7)/8;
switch(length%8){
case 0: do{ *to++ = 0.0;
case 7: *to++ = 0.0;
case 6: *to++ = 0.0;
case 5: *to++ = 0.0;
case 4: *to++ = 0.0;
case 3: *to++ = 0.0;
case 2: *to++ = 0.0;
case 1: *to++ = 0.0;
}while(--n>0);
}
}
-
8This probably made you cool when Tom Duff came out with it. Nowadays it probably makes the other programmers hate you. And (both) rightly so.– sbiSep 4, 2009 at 9:59
-
4
-
1
-
4
-
4memset is probably faster. Some compilers implement it in assembly and do 128bit moves with cache prefetching. Can't really beat that.– user21037Jan 13, 2011 at 19:07
Assuming the loop length is an integral constant expression, the most probable outcome it that a good optimizer will recognize both the for-loop and the memset(0). The result would be that the assembly generated is essentially equal. Perhaps the choice of registers could differ, or the setup. But the marginal costs per double should really be the same.
-
8I tested this with visual c++ and found that "std::fill_n(d, 1000000, 0.0f)" indeed compiles to xor edx, edx mov r8d, 8000000 ; 007a1200H mov rcx, rax call memset So for efficiency there really is no difference at all– jcoderJan 4, 2010 at 11:54
In addition to the several bugs and omissions in your code, using memset is not portable. You can't assume that a double with all zero bits is equal to 0.0. First make your code correct, then worry about optimizing.
-
4You can make that assumption if you are using IEEE-754, and there are very few reasons to justify trying to make your floating-point code tolerant of implementations that wildly differ from the IEEE standard. In fact, the only reason I can imagine tolerating less than full compliance is if you are writing gpgpu code targeting a platform that doesn't implement all the rounding modes and NaN handling according to spec. Sep 3, 2009 at 15:04
-
3@unknown: Well, it's usually IEEE-754, but not always. So make sure by including
BOOST_STATIC_ASSERT(numeric_limits<double>::is_iec559);
somewhere in your code. Then things will fail fast if the assumption is wrong. Sep 4, 2009 at 3:34 -
1@j_random_hacker Yeah, way late here, but Boost here is utterly nonsensical. Adding a dependency to Boost is bad enough, but limiting yourself to only MSVC, GCC, CLang, and Intel C++ (and ignoring C entirely...) is going to help portability how? Because those are the only compilers Boost supports. Sep 8, 2020 at 11:32
-
@AndrewHenle: How you achieve fail-fast is not really important -- the point is to check your assumptions at compile time if at all possible. Modern C++ hass
static_assert
, which avoids the Boost dependency, and I just found out that C11 has_Static_assert()
. Sep 8, 2020 at 12:27
memset(d,0,10*sizeof(*d));
is likely to be faster. Like they say you can also
std::fill_n(d,10,0.);
but it is most likely a prettier way to do the loop.
-
+1 for using count * sizeof, but you should drop the parenthesis too. :)– unwindSep 3, 2009 at 13:26
-
14Note that, AFAIK, the standard doesn't guarantee that 0.0 is implemented as all bits set to 0. (In fact, all bits set to 0 might be an invalid floating point value that's trapped by the hardware.) So filling double with zeroed bytes is not portable and
std::memset()
shouldn't be used.– sbiSep 3, 2009 at 13:27 -
-
2I prefer the
fill_n
way, since that one stays in the same context as thedouble
variable.– xtoflSep 3, 2009 at 13:34 -
3Although I'm sure that "memset(d, length, 0);" is still much faster by far ;)– stefaanvSep 3, 2009 at 15:43
calloc(length, sizeof(double))
According to IEEE-754, the bit representation of a positive zero is all zero bits, and there's nothing wrong with requiring IEEE-754 compliance. (If you need to zero out the array to reuse it, then pick one of the above solutions).
-
3To make sure your assumption is correct, include
BOOST_STATIC_ASSERT(numeric_limits<double>::is_iec559);
somewhere in your code. Sep 4, 2009 at 3:35
According to this Wikipedia article on IEEE 754-1975 64-bit floating point a bit pattern of all 0s will indeed properly initialize a double to 0.0. Unfortunately your memset code doesn't do that.
Here is the code you ought to be using:
memset(d, 0, length * sizeof(double));
As part of a more complete package...
{
double *d;
int length = 10;
d = malloc(sizeof(d[0]) * length);
memset(d, 0, length * sizeof(d[0]));
}
Of course, that's dropping the error checking you should be doing on the return value of malloc. sizeof(d[0])
is slightly better than sizeof(double)
because it's robust against changes in the type of d.
Also, if you use calloc(length, sizeof(d[0]))
it will clear the memory for you and the subsequent memset will no longer be necessary. I didn't use it in the example because then it seems like your question wouldn't be answered.
-
Doesn't the 0 need to be the 2nd argument to memset? Doesn't calloc clear what it allocates to zero? Sep 3, 2009 at 16:45
-
Oops. I should've been more careful with memset. I'll fix that. You're also right about calloc... That's an interesting observation. I'll change the code to use malloc, then mention calloc as an option. Sep 3, 2009 at 17:30
-
1However, the more important point is that C/C++ do not mandate IEEE 754 floating point! Although it is the most common representation, it is perfectly OK for a conforming compiler to use a different representation where all-bits-off in fact represents -42.69, so this code is not portable. Sep 4, 2009 at 3:27
-
So don't drop the error checking. How hard is it to add "if (d) " in front of the memset. It's just 7 chars. It took you far more than 7 chars to note the lack of error checking. (And don't mention dangling elses, the block ends after the memset.) Sep 4, 2009 at 5:15
-
1Adding error checking increases the complexity of the example. Clarity is more important than having the code be exactly correct when you're trying to show something. Sep 4, 2009 at 16:31
Memset will always be faster, if debug mode or a low level of optimization is used. At higher levels of optimization, it will still be equivalent to std::fill or std::fill_n. For example, for the following code under Google Benchmark: (Test setup: xubuntu 18, GCC 7.3, Clang 6.0)
#include <cstring>
#include <algorithm>
#include <benchmark/benchmark.h>
double total = 0;
static void memory_memset(benchmark::State& state)
{
int ints[50000];
for (auto _ : state)
{
std::memset(ints, 0, sizeof(int) * 50000);
}
for (int counter = 0; counter != 50000; ++counter)
{
total += ints[counter];
}
}
static void memory_filln(benchmark::State& state)
{
int ints[50000];
for (auto _ : state)
{
std::fill_n(ints, 50000, 0);
}
for (int counter = 0; counter != 50000; ++counter)
{
total += ints[counter];
}
}
static void memory_fill(benchmark::State& state)
{
int ints[50000];
for (auto _ : state)
{
std::fill(std::begin(ints), std::end(ints), 0);
}
for (int counter = 0; counter != 50000; ++counter)
{
total += ints[counter];
}
}
// Register the function as a benchmark
BENCHMARK(memory_filln);
BENCHMARK(memory_fill);
BENCHMARK(memory_memset);
int main (int argc, char ** argv)
{
benchmark::Initialize (&argc, argv);
benchmark::RunSpecifiedBenchmarks ();
printf("Total = %f\n", total);
getchar();
return 0;
}
Gives the following results in release mode for GCC (-O2;-march=native):
-----------------------------------------------------
Benchmark Time CPU Iterations
-----------------------------------------------------
memory_filln 16488 ns 16477 ns 42460
memory_fill 16493 ns 16493 ns 42440
memory_memset 8414 ns 8408 ns 83022
And the following results in debug mode (-O0):
-----------------------------------------------------
Benchmark Time CPU Iterations
-----------------------------------------------------
memory_filln 87209 ns 87139 ns 8029
memory_fill 94593 ns 94533 ns 7411
memory_memset 8441 ns 8434 ns 82833
While at -O3 or with clang at -O2, the following is obtained:
-----------------------------------------------------
Benchmark Time CPU Iterations
-----------------------------------------------------
memory_filln 8437 ns 8437 ns 82799
memory_fill 8437 ns 8437 ns 82756
memory_memset 8436 ns 8436 ns 82754
TLDR: use memset unless told you absolutely have to use std::fill or a for-loop, at least for POD types which are not non-IEEE-754 floating-points. There are no strong reasons not to.
(note: the for loops counting the array contents are necessary for clang not to optimize away the google benchmark loops entirely (it will detect they're not used otherwise))
-
For avoiding optimization of your code of interest, you can use those functions: gist.github.com/AlexisTM/2754f6b373bf40b544408a631abeb5ba This is from a talk from Chandler Carruth on optimization: youtube.com/watch?v=nXaxk27zwlk&t=2446s Jun 11, 2021 at 6:11
The example will not work because you have to allocate memory for your array. You can do this on the stack or on the heap.
This is an example to do it on the stack:
double d[50] = {0.0};
No memset is needed after that.
-
2Spelling it out: if you supply an initialiser for an aggregate (struct or array), C and C++ will zero-initialise any remaining members. Sep 5, 2009 at 12:44
Don't forget to compare a properly optimized for loop if you really care about performance.
Some variant of Duff's device if the array is sufficiently long, and prefix --i not suffix i-- (although most compilers will probably correct that automatically.).
Although I'd question if this is the most valuable thing to be optimising. Is this genuinely a bottleneck for the system?
-
3I think for primitive types it doesn't matter whether it's prefix or suffix (as long as result isn't used), but it's nice to develop an habit of using prefix whenever you don't care about the result — next loop may employ some complicated iterator instead. Sep 3, 2009 at 13:29
-
Unrolled loops tend to suffer if they are bigger than the CPU's code cache line size.– user246672Dec 2, 2014 at 1:28
memset(d, 10, 0) is wrong as it only nulls 10 bytes. prefer std::fill as the intent is clearest.
-
18
-
1
-
1I do not hold anything against
std::fill
, but how is it another reason? Sep 3, 2009 at 13:27 -
1With memset, I always forget the order of the parameters, which I took over from the question.– stefaanvSep 3, 2009 at 13:36
-
2I'm now considering, on principle, never again using any function that takes two integer parameters. Possible exception if the order doesn't matter, so std::min is OK ;-) Sep 3, 2009 at 14:16
In general the memset is going to be much faster, make sure you get your length right, obviously your example has not (m)allocated or defined the array of doubles. Now if it truly is going to end up with only a handful of doubles then the loop may turn out to be faster. But as get to the point where the fill loop shadows the handful of setup instructions memset will typically use larger and sometimes aligned chunks to maximize speed.
As usual, test and measure. (although in this case you end up in the cache and the measurement may turn out to be bogus).
One way of answering this question is to quickly run the code through Compiler Explorer: If you check this link, you'll see assembly for the following code:
void do_memset(std::array<char, 1024>& a) {
memset(&a, 'q', a.size());
}
void do_fill(std::array<char, 1024>& a) {
std::fill(a.begin(), a.end(), 'q');
}
void do_loop(std::array<char, 1024>& a) {
for (int i = 0; i < a.size(); ++i) {
a[i] = 'q';
}
}
The answer (at least for clang
) is that with optimization levels -O0
and -O1
, the assembly is different and std::fill
will be slower because the use of the iterators is not optimized out. For -O2
and higher, do_memset
and do_fill
produce the same assembly. The loop ends up calling memset
on every item in the array even with -O3
.
Assuming release builds tend to run -O2
or higher, there are no performance considerations and I'd recommend using std::fill
when it's available, and memset
for C.
If you're required to not use STL...
double aValues [10];
ZeroMemory (aValues, sizeof(aValues));
ZeroMemory at least makes the intent clear.
-
5
-
@xtofl: It's probably not the case here but for example when using an older Symbian version, there is no STL available.– foraidtSep 3, 2009 at 13:49
-
@onebyone - but ZeroMemory() has to be among the easiest functions to write out there. Sep 4, 2009 at 0:21
-
-
It's a macro that exapnds to a memset call. I just prefer it because it makes the intent clear, especially to a reader who isn't C-fluent. Sep 4, 2009 at 11:28
As an alternative to all stuff proposed, I can suggest you NOT to set array to all zeros at startup. Instead, set up value to zero only when you first access the value in a particular cell. This will stave your question off and may be faster.
-
How would it be faster? If the array truly needs to be zeroed out, then doing it on the fly would require a separate data structure to keep track of which entries are dirty, and lookups in that data structure would almost certainly take longer than just writing the zeros. Sep 3, 2009 at 23:39
-
If you actually access first 100 cells out of 1 000 000 element array, setting it all to zeros is slower. Especially if instead of that "structure" you just keep track of the lowest uninitialized index.– P ShvedSep 4, 2009 at 2:18
-
How is maintaining a separate structure faster in terms of maintenance? Sep 4, 2009 at 5:17
-
I think you mean
memset(d, 0, length * sizeof(d[0]))
and
for (int i = length; --i >= 0; ) d[i] = 0;
Personally, I do either one, but I suppose std::fill()
is probably better.
-
is fill better because it is faster? I need faster, not more readable :))))– vehomzzzSep 3, 2009 at 13:39
-
I find the latter very cruel and unreadable. Initializing with length and not length-1 and doing the decrement inside the condition. Sep 3, 2009 at 15:01
-
2@enigma: Which is faster? I would have to time it, which you can do also. (Just wrap it in a 10^9 loop and look at your watch - seconds = nanoseconds.) Sep 3, 2009 at 16:24
-
@codymanix: Cruel? Unreadable? (Sounds like ignorant professor-speak.) It's been done that way for ages, and that's how the processors used to do it also - very clean code. Sep 3, 2009 at 16:38
-
1@Mike: One thing to be aware of when you loop downwards like in your 2nd snippet is that the loop will run forever if
i
has unsigned type rather than signed as it does here. Sep 5, 2009 at 12:38
new
is always a good idea:new double[N]()
std::fill
with gcc for x86: to a normal loop with 8B stores. memset and an array initializer both compile torep stosq
. clang likes to use AVX stores, rather than rep stosq, though. Fun fact: gcc will optimizemalloc; memset ( ..., 0, ...)
tocalloc
, but clang doesn't. clang compilesstd::fill
into a call tomemset
, though.g++
appears to optimisestd::fill_n()
intomemset()
; I have a function that zeroes out a memory buffer, and without optimisations said function represents 50% of thecallgrind
time, but with optimisations it's nowhere to be seen... but there magically appear about 3% of calls (beyond other random stuff in supporting libs) to__memset_sse2_unaligned
.