Pythonã§ä½¿ãrangeã¨xrangeã«ã¤ãã¦
çããããã«ã¡ã¯
ãå
æ°ã§ãããç§ã¯å
æ°ã§ãã
ãã¦ãä»æ¥ã¯rangeã¨xrangeã«ã¤ãã¦è¦ã¦ã¿ã¾ãããã
ãã¦ãPythonã使ã人ã§ããã°ããã®ï¼ã¤ãã使ãã¾ããã
Pythonã§ããè¦ãã³ã¼ãã¯ãã¡ãã§ãã
for i in xrange(100): print i
ãã¡ããrangeã§æ¸ã人ãããã¨æãã¾ãããªãã¨ãªã¼ãxrangeã®æ¹ããããã¨è¨ããã¦ãããããããããã¾ããã
æ£ç´ãç§ã¯ãã®ï¼ã¤ä½ãéãã®ãããããã£ã¦ããã¾ãããããã§èª¿ã¹ã¦ã¿ãããªã¨æãããã®è¨äºãè¨è¼ãã¦ãã¾ããã
ã¾ãã¯ãã³ã³ã½ã¼ã«ä¸ããå®è¡ãã¦ã¿ã¾ããã
>>> xrange(10) xrange(10) >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
xrangeã¯ããããããªãçµæã§ãããrangeã§ã¯ãªã¹ããè¿ãããã§ããã
ãã®é¢æ°ã¯ range() ã«é常ã«ããä¼¼ã¦ãã¾ããããªã¹ãã®ä»£ããã« âxrange ãªãã¸ã§ã¯ãâ ãè¿ãã¾ãã ãã®ãªãã¸ã§ã¯ãã¯ä¸éæãªã·ã¼ã±ã³ã¹åã§ã対å¿ãããªã¹ãã¨åãå¤ãæã¡ã¾ããããããã®å¤å ¨ã¦ãåæã«è¨æ¶ãã¾ããã ragne() ã«å¯¾ãã xrange() ã®å©ç¹ã¯å¾®ã ãããã®ã§ã (xrange() ã¯è¦æ±ã«å¿ãã¦å¤ãçæããããã§ã) ãã ããã¡ã¢ãªéã®å³ããè¨ç®æ©ã§å·¨å¤§ãªç¯å²ã®å¤ã使ãæãã(ã«ã¼ãããã break ã§ä¸æãããã¨ãã£ãããã«) ç¯å²ä¸ã®å ¨ã¦ã®å¤ã使ãã¨ã¯éããªãå ´åã¯ãã®éãã§ã¯ããã¾ããã( [http://docs.python.jp/2/library/functions.html#xrange:title]ãã)
ãï¼è¦ã¯ãªã¹ããä½ããã«ããã«å¯¾å¿ãã¦å®è¡ããæã«å¤ãä½ã£ã¦ããã¨ãããã¨ã§ããããã
ãªããå¤ããªã£ããé
ããªãæ°ãããã®ã¯æ°ã®ããã§ããããã
å®é¨ç°å¢
OS:X 10.9.2
CPU:2.8GHz IntelCore i7
ã¡ã¢ãª:16GB 1600MHz DDR3
å®é¨å 容
xrange,rangeã§ã®é度æ¯è¼
ç¹ã«ä½ããã¦ã¾ãããé·ã10000ã®ãªã¹ãã§æ¯è¼ãã¾ããã
ã½ã¼ã¹ã³ã¼ã
import numpy as np import time Time = 10 N = 10000 def list_sum_range(array): for i in range(Time): for j in range(len(array)): j def list_array_sum_xrange(array): for i in range(Time): for j in xrange(len(array)): j if __name__ == '__main__': array = [i for i in xrange(N)] list_array = [array,array] list_function = [list_sum_range,list_array_sum_xrange] for array,function in zip(list_array,list_function): start = time.time() function(array) print "%s" % ((time.time() - start) / Time)
çµæ
å®é¨ | é度 |
range | 0.000310301780701 |
xrange | 0.000260400772095 |
èå¯
xrangeã®æ¹ãæ©ãã§ãããå¿
è¦ã«å¿ãã¦å¤ãåãåºãã¦ãããããªã®ã§ããããã
ä½ããã¡ã¢ãªã¯ééããªãxrangeãå°ãªãã®ã§ãã¡ã¢ãªã大éæ¶è²»ããå ´é¢ã§ã¯xrangeã使ã£ã¦ããã¾ãããã