4 ms·
Loops of known size is the one of the best hints you can give to your compiler though. If the computation inside the loop isn't too complicated, the compiler wi
by m0zg 7y ago
Loops of known size is the one of the best hints you can give to your compiler though. If the computation inside the loop isn't too complicated, the compiler will unroll these, often resulting in amazing speedups. In fact if you know that your array is pretty long but don't know its size, it's often worthwhile to structure the computation as a nested loop, where the inner loop processes chunks of known length (which should be fairly short, and picked to utilize the widest SIMD on your target CPU, e.g. 8 for fp32 on most Intel chips). Then when you run out of chunks you "mop up" at the end. Furthermore, if your chunk size is a power of 2 (which it should be), don't be afraid of the modulo operator (which is normally very slow): the compiler will automatically apply the x % chunk_size == x & (chunk_size - 1) trick for you. All of the above obviously only works if chunk size is known at compile time.
- roelschroeven 7y agoGood modern compilers do all of that for you, even for unknown sizes. For example, see how clang unloops (and vectorizes) a simple loop: https://godbolt.org/z/NPfnhb https://godbolt.org/z/NPfnhb
- m0zg 7y agoYes, in trivial cases like this one, the compiler will generate assembly that's hard to improve upon. But if there were more meat on the bones there (as there is, most of the time, if you aren't just summing ints), this technique could help. As always, benchmark before and after and keep the best variant.