実行速度(改)で、最適化をし尽くしたつもりが、早速 mohayonao@hatena さんから、改善案をいただきました。rangeではなく、xrangeを使うとより高速化するとのこと。早速書き換えてみたところ、2割ほど処理時間を短縮できました。数値解析などでPythonを利用するのであればよさそうです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | >>> profile.run('sum(xrange(1,10000001))') 4 function calls in 0.811 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.811 0.811 0.811 0.811 :0(sum) 1 0.000 0.000 0.811 0.811 <string>:1(<module>) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 0.811 0.811 profile:0(sum(xrange(1,10000001))) >>> profile.run('sum(range(1,10000001))') 5 function calls in 1.049 CPU seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.155 0.155 0.155 0.155 :0(range) 1 0.000 0.000 0.000 0.000 :0(setprofile) 1 0.794 0.794 0.794 0.794 :0(sum) 1 0.100 0.100 1.049 1.049 <string>:1(<module>) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 1.049 1.049 profile:0(sum(range(1,10000001))) |
xrange 型は値の変更不能なシーケンスで、広範なループ処理に 使われています。xrange 型の利点は、 xrange オブジェクトは 表現する値域の大きさにかかわらず常に同じ量のメモリしか占めないということです。 はっきりしたパフォーマンス上の利点はありません。
XRange オブジェクトは非常に限られた振る舞い、すなわち、インデクス検索、反復、 len() 関数のみをサポートしています。