Have been learning Rust by writing simple programs and comparing them with corresponding C variants.
Turned out that simple loop runs 3x times slower in rust than in c , compiled with rustc and g /clang accordingly. Having investigated the issue it appears to be connected to the fact that, unlike g , rustc does not emit avx instructions.
I've tried adding -C target-feature= avx
to rustc flags, but it was in vain.
As far as I'm concerned rustc uses llvm backend, so it should be able to emit them, which leads me to the question: Is avx considered unsafe to use in rust or am I missing a correct way to force rustc to enable avx?
Below I provide program source code and other relevant information:
Rust program and compilation flags:
rustc -C opt-level=3
use std::time;
const N: i32 = 2000;
fn main() {
println!("n: {}", N);
let start = time::Instant::now();
let mut count: i32 = 0;
for a in 1..=N {
for b in 1..a {
for c in 1..=b {
if a*a == b*b c*c {
count = 1;
}
}
}
}
let duration = start.elapsed();
println!("found: {}", count);
println!("elapsed: {:?}", duration);
}
Output:
n: 2000
found: 1981
elapsed: 1.382231558s
C program and compilation flags:
g -O3
clang -O3
#include <iostream>
#include <chrono>
constexpr int N = 2000;
constexpr double MS_TO_SEC = 1e-3;
int main(int argc, char **argv) {
std::cout << "n: " << N << std::endl;
auto start = std::chrono::high_resolution_clock::now();
int count = 0;
for (int a = 1; a <= N; a) {
for (int b = 1; b < a; b) {
for (int c = 1; c <= b; c) {
if (a*a == b*b c*c) {
count = 1;
}
}
}
}
auto elapsed = std::chrono::high_resolution_clock::now() - start;
std::cout << "found: " << count << std::endl;
std::cout << "elapsed: "
<< double(std::chrono::duration_cast<std::chrono::milliseconds>(elapsed).count())*MS_TO_SEC
<< "s" << std::endl;
}
Output:
n: 2000
found: 1981
elapsed: 0.419s
Compiler versions:
g 9.4.0
clang 10.0.0
rustc 1.64.0-nightly
CPU information:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Byte Order: Little Endian
Address sizes: 39 bits physical, 48 bits virtual
CPU(s): 8
On-line CPU(s) list: 0-7
Thread(s) per core: 2
Core(s) per socket: 4
Socket(s): 1
NUMA node(s): 1
Vendor ID: GenuineIntel
CPU family: 6
Model: 60
Model name: Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz
Stepping: 3
CPU MHz: 800.000
CPU max MHz: 3500,0000
CPU min MHz: 800,0000
BogoMIPS: 4988.85
Virtualization: VT-x
L1d cache: 128 KiB
L1i cache: 128 KiB
L2 cache: 1 MiB
L3 cache: 6 MiB
NUMA node0 CPU(s): 0-7
Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs
bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_
deadline_timer aes xsave avx f16c rdrand lahf_lm abm cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1
avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts md_clear flush_l1d
EDIT: @PitaJ suggested adding -mavx2 to c flags, rust is not 9x times slower...
SOLUTION FOUND:
@PitaJ in the comment section found a solution: you have to use both -C target-feature= avx2
or any other simd mechanism and refrain from using inclusive ranges like (1..=N) to get vectorization.
CodePudding user response:
Inclusive ranges are known to be a cause of missed optimizations and performance issues in Rust. See this issue. This applies to your case.
You will need to convert all inclusive ranges from ..=x
to the respective exclusive form ..(x 1)
. Note that this is only possible if x
is less than the maximum value of the integer you're using.
use std::time;
const N: i32 = 2000;
fn main() {
println!("n: {}", N);
let start = time::Instant::now();
let mut count: i32 = 0;
for a in 1..(N 1) {
for b in 1..a {
for c in 1..(b 1) {
if a*a == b*b c*c {
count = 1;
}
}
}
}
let duration = start.elapsed();
println!("found: {}", count);
println!("elapsed: {:?}", duration);
}
If you take a look at the following Compiler Explorer diff, you will see that this makes the hot loop practically identical to that emitted by Clang: https://godbolt.org/z/q69KWh7sx
You'll also need to enable SIMD with -C target-feature= avx
(or avx2
, etc), as I think by default rustc emits portable binaries by default (SIMD instructions are not necessarily portable).
You can also use -C target-cpu=native
to use the maximal features available on your CPU.