Skip to content

Instantly share code, notes, and snippets.

@Torrencem
Created June 4, 2019 14:51
Show Gist options
  • Save Torrencem/8776884ce3fe15f3f76f55b92c0e30c4 to your computer and use it in GitHub Desktop.
Save Torrencem/8776884ce3fe15f3f76f55b92c0e30c4 to your computer and use it in GitHub Desktop.
Optimization example
#![feature(asm)]
use std::env::args;
#[cfg(target_arch = "x86_64")]
fn main() {
match args().nth(1).unwrap().as_ref() {
"a" => fa(),
"b" => fb(),
x => panic!("unknown arg: {}", x),
}
}
fn fa() {
println!("Starting!");
let mut x = 0u32;
for i in 0..1_000_000_000u64 {
if i % 3 == 0 {
x += 1;
}
}
println!("{}", x);
println!("Done!");
}
fn fb() {
println!("Starting 2!");
let mut x = 0u32;
for i in 0..1_000_000_000u64 {
unsafe {
// ASM Equivelent naively
asm!("mov rdx, 0
mov rcx, 3
div rcx
cmp rdx, 0
jne .out
add rbx, 1
.out:
nop" : "={rbx}"(x) : "{rax}"(i), "{rbx}"(x) : "rcx", "rax", "rbx", "rdx", "cc" : "intel");
}
}
println!("{}", x);
println!("Done 2!");
}
#[cfg(not(target_arch = "x86_64"))]
fn main() {
println!("Unsupported target");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment