3 ms·
The benchmark should use std::vector::at() in that case. at() performs bounds checks. http://en.cppreference.com/w/cpp/container/vector/at http://en.cppreferen
by jevinskie 11y ago
The benchmark should use std::vector::at() in that case. at() performs bounds checks.
http://en.cppreference.com/w/cpp/container/vector/at http://en.cppreference.com/w/cpp/container/vector/at
- masklinn 11y agoAs one would expect, the reallocations way dominate the costs: here's the original program > time ./test_cpp 9999010000 ./test_cpp 2.29s user 0.86s system 99% cpu 3.170 total here's by replacing []-indexing by at: > time ./test_cpp_at 9999010000 ./test_cpp_at 2.31s user 0.85s system 99% cpu 3.173 total and here's the second one with vectors reserved to 1000000: > time ./test_cpp_at 9999010000 ./test_cpp_at 1.27s user 0.30s system 98% cpu 1.587 total I expect with iterators and iterator transforms an actual C++ developers could get pretty much the same no-alloc thing I got using them in Rust: > time ./test_rust 9999010000 ./test_rust 0.53s user 0.01s system 97% cpu 0.556 total And of course you could just remove the entirely unnecessary initial loops and just do the summation on the index values anyway because that's what's in your vectors, at which point the compiler realises it's a constant (or it doesn't — I didn't actually check ‚ but it just has 10000 iterations to run with 3 additions each so there isn't much of a difference between that and a constant on a superscalar GHz+ CPU where everything fits handily into registers because there's only two values and a constant): > time ./test_cpp 9999010000 ./test_cpp 0.00s user 0.00s system 45% cpu 0.009 total though assuming you didn't know the upper bound (or the step) I assume there's a formula which gives you the result in constant time.