Skip to content

Instantly share code, notes, and snippets.

@tana
Created November 5, 2014 03:38
Show Gist options
  • Save tana/87ed4c79e7d6a911566a to your computer and use it in GitHub Desktop.
Save tana/87ed4c79e7d6a911566a to your computer and use it in GitHub Desktop.
ifとmatchで階乗を書いて、実行時間を比べてみる。
extern crate time;
fn factorial(n: uint) -> uint {
if n > 1 {
n * factorial(n - 1)
} else {
n
}
}
fn factorial_match(n: uint) -> uint {
match n {
0 | 1 => n,
_ => n * factorial(n - 1)
}
}
fn main() {
loop {
let if_start = time::get_time();
for _ in range(0, 10000u) {
for _ in range(0, 1000u) {
let _ = factorial(10);
}
}
let if_end = time::get_time();
println!("if {}", if_end - if_start);
let match_start = time::get_time();
for _ in range(0, 10000u) {
for _ in range(0, 1000u) {
let _ = factorial_match(10);
}
}
let match_end = time::get_time();
println!("match {}", match_end - match_start);
}
}
@nida-001
Copy link

nida-001 commented Nov 5, 2014

クソリプで失礼しますが,14行目の関数呼び出しで factorial_matchを呼び出さないと比較にならないのでは?

@tana
Copy link
Author

tana commented Jul 10, 2016

ああああ・・・
完全に間違ってました

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment