首先我无意引战,但是今天看到某位同学的文章里有某些错误,不得不指正一下。
原文地址:http://studygolang.com/articles/9628
1. 测量时间的时候我们使用 `std::time::SystemTime::elapsed` 即可,不必蹩脚的使用两个 system 输出出来还得手动算一下。(当然你说对Rust不熟也就无所谓了)
2. 最重要一点。 执行 rust 代码的时候请用 `--release` ,cargo 项目请直接执行 `cargo run --release`
在我本机的测试过程:
```
➜ demo pwd
/Users/wayslog/go/src/demo
➜ demo go version
go version go1.7.1 darwin/amd64
➜ demo cat demo.go
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
runtime.GC()
t := time.Now()
sum := 0
for i := 0; i < 20000; i++ {
for j := 0; j < 20000; j++ {
sum = sum + i*j
}
}
fmt.Println(time.Now().Sub(t))
fmt.Println(sum)
}
➜ demo go run demo.go
236.312079ms
39996000100000000
➜ demo go build
➜ demo ./demo
289.696142ms
39996000100000000
➜ demo cd ~/rust/baka
➜ baka git:(master) ✗ cat src/main.rs
use std::time::SystemTime;
fn main() {
let sys_time = SystemTime::now();
let mut x = 0;
let mut i = 0;
let mut y: u64 = 0;
while x < 20000 {
i = 0;
while i < 20000 {
y = y + x * i;
i = i + 1;
}
x = x + 1;
}
println!("{:?}", sys_time.elapsed());
println!("The value of y is: {}", y);
}
➜ baka git:(master) ✗ cargo run --release
Finished release [optimized] target(s) in 0.0 secs
Running `target/release/baka`
Ok(Duration { secs: 0, nanos: 0 })
The value of y is: 39996000100000000
➜ baka git:(master) ✗ cargo build --release
Finished release [optimized] target(s) in 0.0 secs
➜ baka git:(master) ✗ ./target/release/baka
Ok(Duration { secs: 0, nanos: 0 })
The value of y is: 39996000100000000
```
Rust这里为什么会跑到0秒0ns呢?
将rust编译到asm我们能看到, 地址在这:https://is.gd/CyE36H:
```
movabsq $39996000100000000, %rax
```
编译时计算掉了么?
OK,既然编译时计算掉了这个情况,那么,我们让用户自己输入数字吧,这样编译时计算总优化不掉吧?
```
➜ baka git:(master) ✗ cat src/main.rs
use std::time::SystemTime;
use std::env;
fn main() {
let mut args = env::args();
args.next().unwrap();
let max_range = args.next().unwrap().parse::<u64>().expect("not num");
let sys_time = SystemTime::now();
let mut x = 0;
let mut i = 0;
let mut y: u64 = 0;
while x < max_range {
i = 0;
while i < max_range {
y = y + x * i;
i = i + 1;
}
x = x + 1;
}
println!("{:?}", sys_time.elapsed());
println!("The value of y is: {}", y);
}
➜ baka git:(master) ✗ cargo build --release
Finished release [optimized] target(s) in 0.0 secs
➜ baka git:(master) ✗ ./target/release/baka 20000
Ok(Duration { secs: 0, nanos: 6000 })
The value of y is: 39996000100000000
➜ baka git:(master) ✗ ./target/release/baka 40000
Ok(Duration { secs: 0, nanos: 12000 })
The value of y is: 639968000400000000
```
这里,Rust编译器可能也做了其他的优化了,但是需要分析asm再来看了,这里不做赘述。
但是,无论怎么看, 6000 ns (0.006ms) 和 200 ms 都是数量级的差距吧?
总结一点,不会别瞎说,这位 gopher 不行啊,深表同情。
有疑问加站长微信联系(非本文作者)