Coding/Python Matlab

python vs cpp speed test

smores 2017. 7. 18. 12:01

파이썬을 많이 사용하다보니 여러가지 편한 점 때문에 점점 CPP 사용이 뜸해져서 심지어 간단한 문법도 잊어버리는 것을 느꼈다.


다양한 데이터의 너무도 수월한 처리 능력에 파이썬을 많이 쓰기는 하지만, 간혹 상당히 부하가 많이 걸릴만한 수치계산이 필요한 경우가 있다. 그래서 간단한 코드로 수학 연산(삼각함수)의 속도 비교를 해 보았다. 사용한 툴들은 CPP 의 경우 Borland C++ 5.5 command line compiler 와 Anaconda 4.4.0 64비트에 포함된 Python 2.7.13 이고 둘 다 Windows 10 Pro 64bit 환경에서 돌렸다. Borland C++ 컴파일시에는 특별히 속도 향상을 위한 컴파일러 옵션은 주지 않고 컴파일한 코드를 사용했다. 속도 비교를 위한 코드는 다음과 같다.



C++


#include <cstdio>

#include <iostream>

#include <cmath>

#include <time.h>

using namespace std;


void main()

{

  int i,j;

  double x;

  clock_t start = clock();

  for (i=0;i<10000;i++)

  {

    for (j=0;j<10000;j++)

    {

      x = sin(cos(sin(13*3.14)));

    }    

    if (i % 100 == 0)

      cout << i << endl;

  }

  printf("Time elapsed: %f\n", ((double)clock()-start)/CLOCKS_PER_SEC);

}



Python


from math import sin,cos

import time


starttime = time.time()


for i in range(10000):

    for j in range(10000):

        x = sin(cos(sin(13*3.14)))

    if i % 100 == 0:

        print i


elapsedtime = time.time() - starttime

print 'Time elapsed:', elapsedtime




아, 역시 파이썬 코드는 간결하다.


그런데 실행 결과는...


C++

.

.

9300

9400

9500

9600

9700

9800

9900

Time elapsed: 10.234000

Press any key to continue . . .


Python

.

.

9300

9400

9500

9600

9700

9800

9900

Time elapsed: 38.6819999218



거의 4배의 차이가 난다. 


이래서 역시 대규모의 수치 연산을 하려면 아무래도 C++을 포기할 수 없을 것 같다.




'Coding > Python Matlab' 카테고리의 다른 글

deepcopy  (0) 2017.10.07
curve fitting, solidworks, LT  (1) 2017.09.23
아나콘다, 선형회귀분석  (0) 2017.06.13
multiple column data reading  (0) 2017.03.14
pip - 윈도우즈 python 에서도 지원  (0) 2017.02.08