人工知性を作りたい

私が日々、挑戦したことや学んだことなどを紹介していく雑記ブログです。 (新しいAI技術HTM, 専門の音声信号処理, 趣味のアニメ等も書いてます。)

PythonとC言語における実行速度の比較!ーfor文・ループ処理

f:id:hiro-htm877:20190616152255j:plain





 

f:id:hiro-htm877:20190601202549p:plain

 「Pythonの処理は遅いっていうけど実際どれくらい遅いの?」

C言語とどれくらい違うの?」

 

 

 

そんな方の疑問に答えます

 

コードが知りたい方は目次のソースコードへ飛んでください!

本記事のテーマ

【完全初心者向け】

PythonC言語における実行速度の比較!

今回はfor文(100000ループ)の中で変数'j'を+1していきます。

PythonC言語の実行速度の比較

実験の流れ

1. C言語によるforループの作成

2. Pythonによるforループの作成

3. 1.2の実行速度を計測

4. 実行速度の比較

PythonC言語の実行速度の比較プログラム実装!

C言語のループ処理

roop.cpp
#include<pybind11/pybind11.h>
int roop() {
  int j=0;
  for(int i=0; i<100000;i++){
    j++;
  }
  return j;
}

PYBIND11_MODULE(test_roop, m) {
    m.doc() = "pybind11 example plugin";
    m.def("roop", &roop, "A function which adds tow numbers");
}

Pythonのループ処理と実行速度の比較

実行速度の計算法

1. import time

2. start = time.time()

 ←基準の時間を代入

3. process_time = time.time - start

 ←測定したい処理後、現在の時間から基準の時間を引いて計算

speedCandPython.py
import time
import test_roop

if __name__ == "__main__" :
    process_time_mean = 0
    start = time.time()
    conclusion = test_roop.roop()
    process_time = time.time() - start

    tmp = process_time    #比較用変数

    start = time.time()
    j=0
    for i in range(100000):
        j+=1
    process_time = time.time() - start
    #Pythonの処理はC言語の何倍か?
    process_time_mean += process_time / tmp

    print (process_time_mean)

出力 (10回分)

$ python speedCandPython.py
314.5944055944056
$ python speedCandPython.py
356.2280701754386
$ python speedCandPython.py
365.14406779661016
$ python speedCandPython.py
345.74074074074076
$ python speedCandPython.py
379.9734513274336
$ python speedCandPython.py
335.9307692307692
$ python speedCandPython.py
324.48837209302326
$ python speedCandPython.py

432.60330578512395
$ python speedCandPython.py
453.8407079646018
$ python speedCandPython.py
309.44029850746267

 

平均: 361.59

完成です!

なんと、ただ1を足し続けるだけで平均361.59倍もPythonの方が遅いことがわかりました。これが機械学習などで3日間かかる処理だとすると(Python

 

3日間 → ( 24 * 60分(1時間) )(1日) * 3日 = 4320分(3日)

C言語でかかる時間: 4320分(3日) / 360(pythonC言語の実行速度比) = 12分

 

なんと!Pythonで3日かかる処理がC言語では12分で終わることが分かりました!

 

今回は単純な計算で行いましたが、実際の機械学習でもC言語でかけるとこを増やせば3日が1日ぐらいにはなると思います。

皆さんも頑張って実行速度を減らし、研究や製品作成速度を上げていきましょう