プリンキピア

第13章計算の性能

13.1. Compilers and Interpreters13.1 コンパイラとインタープリタ

So far, this book has focused on imperative programming, which makes use of statements such as print, +, and if to change a program’s state. Consider the following example of a simple imperative program.
英語のヒント
ここまで、この本は命令型プログラミングに焦点を当ててきた。それは、print、+、ifのような文を使ってプログラムの状態を変える。次の、単純な命令型プログラムの例を考えよう。
def add(a, b):
    return a + b

def fancy_func(a, b, c, d):
    e = add(a, b)
    f = add(c, d)
    g = add(e, f)
    return g

print(fancy_func(1, 2, 3, 4))
10
Python is an interpreted language. When evaluating the above fancy_func function it performs the operations making up the function’s body in sequence. That is, it will evaluate e = add(a, b) and store the results as variable e, thereby changing the program’s state. The next two statements f = add(c, d) and g = add(e, f) will be executed similarly, performing additions and storing the results as variables. Fig. 13.1.1 illustrates the flow of data.
英語のヒント
Pythonはインタープリタ型の言語である。上のfancy_func関数を評価するとき、関数の本体を構成する演算を順に実行する。つまり、e = add(a, b)を評価して結果を変数eとして格納し、それによってプログラムの状態を変える。次の二つの文f = add(c, d)とg = add(e, f)も同じように実行され、足し算を行って結果を変数として格納する。図13.1.1はデータの流れを示している。
Fig. 13.1.1図13.1.1
Data flow in an imperative program.
英語のヒント
命令型プログラムでのデータの流れ。
Although imperative programming is convenient, it may be inefficient. On the one hand, even if the add function is repeatedly called throughout fancy_func, Python will execute the three function calls individually. If these are executed, say, on a GPU (or even on multiple GPUs), the overhead arising from the Python interpreter can become overwhelming. Moreover, it will need to save the variable values of e and f until all the statements in fancy_func have been executed. This is because we do not know whether the variables e and f will be used by other parts of the program after the statements e = add(a, b) and f = add(c, d) are executed.
英語のヒント
命令型プログラミングは便利だが、効率が悪いかもしれない。一方で、add関数がfancy_funcの中で繰り返し呼ばれても、Pythonは三つの関数呼び出しを個別に実行する。これらを、たとえばGPU(あるいは複数のGPU)の上で実行すると、Pythonのインタープリタから生じるオーバーヘッドが圧倒的になりうる。さらに、fancy_funcのすべての文が実行されるまで、eとfの変数の値を保存しておく必要がある。これは、文e = add(a, b)とf = add(c, d)が実行された後に、変数eとfがプログラムのほかの部分で使われるかどうかがわからないからである。