1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

python, ruby, php, node のループの速さ

Last updated at Posted at 2019-03-05

今日も楽しいマイクロベンチマーク。

某所で python の for ループが遅いという話を聞いたので、そうなの? と思って他の言語と比べてみた。

ソース

python3

python3
import sys
r=0
for i in range(int(sys.argv[1])):
  r+=1
print(r)

PHP

<?php
$len = (int)$argv[1];
$r=0;
for( $i=0 ; $i<$len ; ++$i ){
  ++$r;
}
echo($r);

node.js

node.js
const len = process.argv[2]|0;
let r=0;
for( let i=0 ; i<len ; ++i ){
  ++r;
}
console.log(r);

ruby

ruby2.6
n=ARGV[0].to_i
r=0
n.times do
  r+=1
end
p r

測る人

測る人はわりとやる気ない感じで、Benchmark.realtime を使っている。

bench.rb
require "benchmark"
require "pp"

COMMANDS = [
  [ "php for.php", "php" ],
  [ "node for_pp.js", "node" ],
  [ "python3 for_range.py", "python3" ],
  [ "ruby times.rb", "ruby" ],
]

COUNTS = (10..27).map{ |e| 2**e }

File.open( "result.csv", "w" ) do |f|
  f.puts( (["tick"]+COMMANDS.map{ |cmd| cmd[1] }).join(",") )
  COUNTS.each do |count|
    s=([count]+COMMANDS.map{ |cmd|
      Benchmark.realtime{ %x(#{cmd[0]} #{count}) }
    }).join(",")
    f.puts(s)
    puts(s)
  end
end

各言語のファイル名がいい加減なのがバレるね。

結果

結果は下記グラフの通り。
両対数グラフ注意。

image.png

測る人のソースコードを見ると分かる通り、プログラムの起動時間を含んでいる。
10万回ぐらい回しても、起動時間の影に隠れて殆ど見えないということがわかる。

1.34億回回すのに要する時間を、node.js を 1.00 として表にすると:

php node python3 ruby
Benchmark.realtime そのまま 6.13 1.00 61.72 28.83
起動時間らしきものを減算 10.56 1.00 108.11 50.13

「起動時間らしきものを減算」は、1.34億回の結果から 1024回の結果を減じたもの。

こんな感じ。node 速いね。
そして噂のとおり、python3 は遅いのであった。

あと。PHP だけ起動が速いらしい。そういうものか。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?