僕の備忘録(PC、UN*X、ネットワーク関連が中心)なんです。
自分の書いたところは適当(な時とか)に書き換えますので御了承を。
ubuntu 12.04 で、for と while を比較してみた。
#!/usr/bin/env python from sys import argv import time try: rtime = int(argv[1]) except: print ("No argv or not int") begin = time.time() for x in range(rtime): pass end = time.time() print ("for loop costs", round(end - begin, 2), "second.") begin = time.time() while rtime > 0: pass rtime -= 1 end = time.time() print ("while loop costs", round(end - begin, 2), "second.")
$ python --version
Python 2.7.3
$ python pass.py 10000000
('for loop costs', 0.99, 'second.')
('while loop costs', 0.98, 'second.')
$ python3 --version
Python 3.2.3
$ python3 pass.py 10000000
for loop costs 0.63 second.
while loop costs 1.31 second.
ちなみにwheezy(python2.5.6c1, python3.2.3)では、
$ python pass.py 10000000
('for loop costs', 1.8400000000000001, 'second.')
('while loop costs', 2.46, 'second.')
$ python3 pass.py 10000000
for loop costs 1.35 second.
while loop costs 3.11 second.
for ループ推奨は 本にも書いてあった気がする。
リンクはご自由にどうぞ。でもURLや内容が変った場合はあしからず。