Repository navigation
Open
Description
With great interest I read the following blog post:
https://lpython.org/blog/2023/07/lpython-novel-fast-retargetable-python-compiler/
But to my surprise I discovered the C++ code in the benchmark of dijkstra_shortest_path is pessimized rather than optimized.
The usage of maps makes this Code much, much slower as it could.
On my system (some ancient i7 laptop), the following is more than 40 times faster (see below) than the original code.
#include <iostream>
#include <vector>
int32_t dijkstra_shortest_path(int32_t n, int32_t source) {
int32_t i, j, v, u, mindist, alt, dummy, uidx;
std::vector<int32_t> dist, prev;
std::vector<bool> visited;
std::vector<int32_t> Q, graph(n*n);
Q.reserve(n);
dist.reserve(n);
prev.reserve(n);
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
graph[n * i + j] = std::abs(i - j);
}
}
for(v = 0; v < n; v++) {
dist.push_back(2147483647);
prev.push_back(-1);
Q.push_back(v);
visited.push_back(false);
}
dist[source] = 0;
while(Q.size() > 0) {
u = -1;
mindist = 2147483647;
for(i = 0; i < Q.size(); i++) {
if( mindist > dist[Q[i]] ) {
mindist = dist[Q[i]];
u = Q[i];
uidx = i;
}
}
Q.erase(Q.begin() + uidx);
visited[u] = true;
for(v = 0; v < n; v++) {
if( v != u and not visited[v] ) {
alt = dist[u] + graph[n * u + v];
if( alt < dist[v] ) {
dist[v] = alt;
prev[v] = u;
}
}
}
}
int32_t dist_sum = 0;
for(i = 0; i < n; i++) {
dist_sum += dist[i];
}
return dist_sum;
}
int main() {
int32_t n = 4000;
int32_t dist_sum = dijkstra_shortest_path(n, 0);
std::cout<<dist_sum<<std::endl;
return 0;
}For convenience, this is the diff:
--- a.cpp 2023-07-30 10:59:17.482487750 +0200
+++ f.cpp 2023-07-30 14:57:58.543699027 +0200
@@ -1,13 +1,15 @@
#include <iostream>
-#include <unordered_map>
#include <vector>
int32_t dijkstra_shortest_path(int32_t n, int32_t source) {
int32_t i, j, v, u, mindist, alt, dummy, uidx;
- std::unordered_map<int32_t, int32_t> graph, dist, prev;
- std::unordered_map<int32_t, bool> visited;
- std::vector<int32_t> Q;
-
+ std::vector<int32_t> dist, prev;
+ std::vector<bool> visited;
+ std::vector<int32_t> Q, graph(n*n);
+ Q.reserve(n);
+ dist.reserve(n);
+ prev.reserve(n);
+
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
graph[n * i + j] = std::abs(i - j);
@@ -15,10 +17,10 @@
}
for(v = 0; v < n; v++) {
- dist[v] = 2147483647;
- prev[v] = -1;
+ dist.push_back(2147483647);
+ prev.push_back(-1);
Q.push_back(v);
- visited[v] = false;
+ visited.push_back(false);
}
dist[source] = 0;Furthermore, I implemented a rust version for comparison.
fn dijkstra_shortest_path(n: i32, source: i32) -> i32 {
let mut dist = Vec::with_capacity(n as usize);
let mut prev = Vec::with_capacity(n as usize);
let mut visited = Vec::with_capacity(n as usize);
let mut q = Vec::with_capacity((n * n) as usize);
let mut graph = vec![0; (n * n) as usize];
for i in 0..n {
for j in 0..n {
graph[(n * i + j) as usize] = (i - j).abs();
}
}
for v in 0..n {
dist.push(2147483647);
prev.push(-1);
q.push(v);
visited.push(false);
}
dist[source as usize] = 0;
let mut u;
let mut uidx = 0;
let mut mindist;
let mut alt;
while q.len() > 0 {
u = -1;
mindist = 2147483647;
for i in 0..q.len() {
let d = dist[q[i] as usize];
if mindist > d {
mindist = d;
u = q[i];
uidx = i;
}
}
q.remove(uidx);
visited[u as usize] = true;
for v in 0..n {
if v != u && !visited[v as usize] {
alt = dist[u as usize] + graph[(n * u + v) as usize];
if alt < dist[v as usize] {
dist[v as usize] = alt;
prev[v as usize] = u;
}
}
}
}
dist.iter().sum()
}
fn main() {
let n = 4000;
let dist_sum = dijkstra_shortest_path(n, 0);
println!("{}\n", dist_sum);
}Benchmark
$ clang++ -std=c++20 -ffast-math -O3 -march=native old.cpp -o old
$ clang++ -std=c++20 -ffast-math -O3 -march=native better.cpp -o better
$ rustc main.rs -C opt-level=3 -o better-rust
$ hyperfine --warmup=20 --min-runs=10 ./old ./better ./better-rust
Benchmark 1: ./old
Time (mean ± σ): 1.690 s ± 0.112 s [User: 1.380 s, System: 0.299 s]
Range (min … max): 1.407 s … 1.790 s 10 runs
Benchmark 2: ./better
Time (mean ± σ): 40.3 ms ± 2.7 ms [User: 31.5 ms, System: 8.2 ms]
Range (min … max): 34.4 ms … 45.8 ms 71 runs
Benchmark 3: ./better-rust
Time (mean ± σ): 40.4 ms ± 1.7 ms [User: 32.8 ms, System: 7.5 ms]
Range (min … max): 37.7 ms … 44.2 ms 68 runs
Summary
./better ran
1.00 ± 0.08 times faster than ./better-rust
41.93 ± 3.97 times faster than ./old
(compilers used: rustc 1.71.0-nightly (2f2c438dc 2023-05-08) and clang version 15.0.7 on ArchLinux)
Reacted by Ondřej Čertík, Jiahao XU, Pranav and Thirumalai Shaktivel
Metadata
Metadata
Assignees
Labels
No labels
Activity
certik commentedon Jul 30, 2023
@oleid awesome, beautiful! Thank you for taking the time to optimize the benchmark, we'll use it.
We'll benchmark against a list based version in LPython as well. I am curious what the results will be.
czgdp1807 commentedon Jul 30, 2023
@oleid Thank you for the optimisation. I would like to mention some points,
dictbecause I wanted to benchmark hash-maps of LPython and C++.listthe way C++ does (by callingreserve). I am not sure Python has the ability to pre-allocate memory forlist. If Python hasn't, then LPython can't support that. By pre-allocation here I mean actually allocating memory in Python for alist. If we want to keep reserve as a no-operation thing (as @certik suggested) in Python then its possible to support it in LPython.So, now I would post 3 codes below,
Without calling
reserveWith calling
reserveEquivalent LPython code (without calling something like
reserve)Final Results
reserve- 1.274 (relative - 1.55)reserve- 0.623 (relative - 0.76)reserve) - 0.822 (relative - 1.0)certik commentedon Jul 30, 2023
It looks like reserve makes a big difference here, so we should support it in LPython as well. For example by
from lpython import list_reserveand just call this function. The CPython implementation will not do anything. I opened up an issue for this at #2232.oleid commentedon Jul 30, 2023
Instead of reserving and calling
push_backin this case one could as well simply initialize directly, as pointed out here: https://www.phoronix.com/forums/forum/phoronix/latest-phoronix-articles/1400748-lpython-is-the-latest-python-implementation-aiming-to-be-very-fast-multiple-backends?p=1400898#post1400898The following is c++20 due to usage of views
I didn't benchmark it, but should be faster.
Also, please note that
vector<bool>is slow in C++, it's a trap.certik commentedon Jul 31, 2023
@oleid great. We'll benchmark the best C++ implementation that you (we) can come up with.
NobodyXu commentedon Jul 31, 2023
@certik I also have a more optimized Rust-version with optimized
Vecinitialization, avoid array bound checking and use of conditional move to avoid branch mis-prediction:Details
oleid commentedon Jul 31, 2023
Interesting, on my system that's actually about 50% slower on my system 🤔
For some reason pushing elements to the graph (although being pre-allocated) is slower than setting the elements to zero and overwriting 🤷
The whole while loop didn't change a thing for me. The compiler seems to be smart enough to eliminate all the bound checks by itself.
Anyway, the following is the fastest rust version on my system (and also in-line with the c++ version posted below):
oleid commentedon Jul 31, 2023
The version with the view didn't work for me. The follwing did:
My original version runs 15% slower than this one.
NobodyXu commentedon Jul 31, 2023
Could it be that conditional move is actually slower than branching in this case?
Perhaps there's just too many if-else in
Vec::pushfor the compiler to optimize themcertik commentedon Jul 31, 2023
@oleid, @NobodyXu, thank you both! We are implementing the "reserve" feature into LPython and we'll redo the benchmarks with your updated codes. I am curious what we will see!
oleid commentedon Jul 31, 2023
Me too! And thanks again for your work on lpython! Very interesting stuff!
maxbachmann commentedon Aug 1, 2023
Python allows you to pre allocate the list at least from the C-API using
PyList_New(https://docs.python.org/3/c-api/list.html#c.PyList_New). However it will be in an invalid state until you actually set all the elements. So either you will need to ensure the proper usage of this partially initialized list, or you simply initialize them to something like None:Maybe from Python something like
[None] * lengenerates somewhat similar bytecode 🤔Cython optimizes from
[None] * lento the code above as long as len is known to be an integer.certik commentedon Aug 1, 2023
@maxbachmann interesting, thanks! We could later see if we should internally transform
[None] * leninto what we are currently implementing in #2238, which will work like this:We don't support None in list elements, so it might create more confusion to use the syntax
[None] * len, so the functionreserveis probably less confusing.maxbachmann commentedon Aug 1, 2023
The optimization is not specific to the None case. Basically whenever it is able to derive the output length it will use it for this kind of optimization. So the same would work for things like
[1] * len. Another case where this can be interesting are comprehensions of known size like e.g.[i for i in range(n)]. The case of list comprehensions is not implemented in Cython yet either (cython/cython#2844).certik commentedon Aug 1, 2023
Excellent point. One worry is if you do
[1] * len, but then the compiler can't infer that all elements will be set, then it will have to do an unnecessary initialization.czgdp1807 commentedon Aug 1, 2023
I tried with #2238. For LPython it hardly produces any difference in timings (with and without reserve). It takes roughly 0.8s. Even for C++ with calling
reserve, on my machine the speed gets improved in multiple runs,Code
The user time is same in all the runs i.e., 0.45s.
Equivalent LPython code (with
reserve)Even in multiple runs, 0.75s is the user timing and system timing is 0.14s.
Machine Specifications - Apple M1 MacBook Pro 2020 Model 8 GB Memory.
czgdp1807 commentedon Aug 1, 2023
So the best timings that I could extract is, 0.8s for LPython and 0.6s for C++ (both having calls to
reserve) for a problem size of 20000. As of now, I don't know how to reduce it further for LPython. I will investigate on this.I might be wrong, but this might be because of the indirections in accessing the list elements in LPython. We represent an
int32_tlist as{i32*, end_point, capacity}. Now whenever we dol[i]. First the first element of the structure is obtained, which gives,i32**, now load it to obtaini32*(memory block residing in heap memory), and finally load thei-thelement from thisi32*. So two extra instructions are executed whenever a list access is made in LPython. It doesn't matter if we remove the struct and use a pointer variable to storei32*data pointer of a list, those two extra instructions will still be there. What we need is to just load the i-th element of a list without any extra overhead.So you can see the difference in user timings, 0.07 and 0.05. 1.4x difference between LPython and C++.
certik commentedon Aug 3, 2023
I think our loop unrolling is making it slower:
This is now a lot faster. We should probably remove it from default optimizations.
After this, let's examine LLVM after all our
--fastpasses are done, but before LLVM applies its optimizations. Then compare Clang's LLVM IR before optimizations.With all LLVM optimizations, here is Clang's LLVM IR:
And here is LPython's LLVM IR:
It looks like Clang's IR is 4 times unrolled.
Let's get LPython's LLVM IR after
--fast, but before applying LLVM optimizations, then pass that LLVM IR to clang with -O3, to obtain the same LLVM passes and then compare if it gets unrolled 4x. Eventually we need to figure out how to tell LLVM ourselves to unroll it properly.Also try using our own unroll pass, but do it 4x.
StefanBruens commentedon Aug 4, 2023
This is invalid code, either specify the size in the constructor (explicit, or via initilizer list or range), or use reserve + push_back.
certik commentedon Aug 4, 2023
Ah that's right! I totally missed it, thank you @StefanBruens. @czgdp1807 can you please fix it? This is invalid for LPython too, let's use this opportunity to check that LPython gives us an out of bounds exception in Debug mode.