r/Cplusplus • • 1d ago

Tutorial Less Code Doesn't Mean Faster Code

/r/cpp/comments/1yac9ay/less_code_doesnt_mean_faster_code/
1 Upvotes

2 comments sorted by

4

u/_side_ 1d ago edited 1d ago

Well the code is not doing the same. For example: (src[0] + src[1]) + (src[2] + src[3]) is not the same as integrating in the for loop over 4 elements with a single accumulator which is ((src[0] + src[1]) + src[2]) + src[3]

Edit: I should add that the throughput difference comes from that (src[0] + src[1]) + (src[2] + src[3]) enables the compiler to pipeline (src[0] + src[1]) followed by (src[2] + src[3]). These do not depend on each other. If T is some primitive like a float or some int they will be SIMD anyways.

1

u/mredding C++ since ~1992. 1d ago

Kind of true, there's a definite truthiness to it. I would use the contrast to investigate why the more concise code is inferior to the expanded implementation, rather than accept the expanded implementation out of hand. We need to answer if we know how to generate better machine code, how come the compiler doesn't? This iterative feedback loop will help us write better code.