Archive for 1月 12th, 2011

Pythonの勉強を始めて2週間が経過

1月 12th, 2011 by admin

 年末年始の5連休、成人式までの3連休など、比較的時間のとりやすい期間だったとはいえ、この2週間でずいぶんPythonのことを理解できてきたとおもう。特に、昨日、今日の、実行速度についての記事を通して、Pythonは「実用的な実行速度」と「ソースコードの可読性」を高いレベルで実現していることを思い知らされた。
 もちろん、数値解析を行うのであれば、コンパイル型の言語を使ったほうが速いだろう。だが、ボトルネックになる処理はごく一部なのだから、その部分だけCなどで作成し、データの入出力などはPythonで実装するのがよいと思う。GoogleAppEngineでのWebアプリケーション開発を目的としているので、昨日、今日とやってきたベンチマークはほとんど役に立たないが、頭の片隅に残しておこうとおもう。

I have been studying Python for about two weeks. I have learned basics of Python so far. I was impressed how Python balance readability and processing speed. It is quite easy to read and fast enough to deal with problems in almost any situation.
Of course, in some cases, like statistical analysis or kind of simulation, we had better use compiling language like C. But the bottleneck is limited, only a very small part of the whole program should be written in native languages. We can make interface program by Python and then we can concentrate on the problem itself.
I want to develop web application so this kind of benchmarking is not important. But it is better to know at least.

xrangeで高速化

1月 12th, 2011 by admin

実行速度(改)で、最適化をし尽くしたつもりが、早速 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)))

3.6.3 XRange 型

xrange 型は値の変更不能なシーケンスで、広範なループ処理に 使われています。xrange 型の利点は、 xrange オブジェクトは 表現する値域の大きさにかかわらず常に同じ量のメモリしか占めないということです。 はっきりしたパフォーマンス上の利点はありません。

XRange オブジェクトは非常に限られた振る舞い、すなわち、インデクス検索、反復、 len() 関数のみをサポートしています。