Coding/Python Matlab

파이썬 - 코드 라인수 및 실행 속도 비교 (텍스트 데이터 처리)

smores 2012. 1. 19. 23:27
파이썬 공부한 지 얼마 지나지 않았지만 벌써 그 간결함과 강력함(나의 사용 용도의 경우)에 푸욱 빠지고 있다.

자주 하는 일 중 하나가 대략 수십만 에서 수백만개 정도의 데이터 값 (x, y 좌표값, 한 라인에 두 숫자만 있음, 첫줄은 헤더) 을 읽고 처리하는 일들이 있다. 그동안은 BorlandC++ 5.5 커맨드라인 버전과EditPlus를 IDE 삼아서 프로그램을 짜서 써왔다. 숫자 데이터를 토큰별로 읽기 위해 loop 안에서 stream reading (<<) 기능을 반복하곤 했는데 이게 시간이 꽤 걸린다 (데이터 갯수가 많아서). 게다가 프로그램 라인수도 간단한 기능에 비해선 꽤 길었던 것 같고... 동일한 일을 파이선으로 해 보고는 그만 반해 버렸다. 다음은 수행속도 비교 및 테스트 코드들...

앞으로 업무에서 하고 있는 상당수의 데이터 처리 유틸리티를 C++에서 파이썬으로 바꾸게 될 것 같다.


파이선 2.7.2 


볼랜드C++ 5.5 

이거 비교해 보고서야 C++코드에 작은 버그 하나 숨어 있었음을 발견 (그리 중요치는 않지만...)
갯수 카운트를 0부터 하는 바람에 전체 포인트 수가 하나 적은 것 보임...  -_-;


C++ 코드
 

#include <fstream>

#include <iostream>

#include <string>

#include <time.h>


using namespace std;


void main()

{

string datafilename;


cout << "input featpos data file name : ";

cin >> datafilename;


clock_t start = clock();

ifstream fin(datafilename.c_str());

if (!fin.is_open()) 

{

cout << "cannot open " << datafilename << endl;

exit(0);

}


// dummy reading

string str;

fin >> str >> str; // X, Y


double x, y;

double xmin, xmax, ymin, ymax;

fin >> x >> y;

xmin = xmax = x;

ymin = ymax = y;

int row = 0;

while(1)

{

fin >> x >> y;

if (fin.eof()) break;

if (x < xmin) xmin = x;

if (x > xmax) xmax = x;

if (y < ymin) ymin = y;

if (y > ymax) ymax = y;

//if (row % 10000 == 0) cout << ".";

row++;

}

fin.close();

cout << endl;


cout << "xmin = " << xmin << endl;

cout << "xmax = " << xmax << endl;

cout << "ymin = " << ymin << endl;

cout << "ymax = " << ymax << endl;

cout << "total number of features = " << row << endl;


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


cin.get();

}




파이썬 코드
 

import time


def ReadFpos(fposname):

try:

f=open(fposname)

except:

print fposname, "open error"

quit()

s=f.read()

f.close()

s1=s.split()

xs=s1[0::2]

ys=s1[1::2]

x=map(float,xs[1:]) # ignore the first item; header

y=[float(v) for v in ys[1:]] # same above different expression

return x, y


def FposMinMax():

fposname = raw_input("fpos file name ? ")

start_time = time.time()

x,y=ReadFpos(fposname)

print "total # pts = %d" % len(x)

xmin,xmax,ymin,ymax = min(x),max(x),min(y),max(y)

print "x_min, x_max = %f, %f" % (xmin, xmax)

print "y_min, y_max = %f, %f" % (ymin, ymax)

elapsed_time = time.time() - start_time

print "elapsed time in sec", elapsed_time



if __name__=="__main__":


FposMinMax()

quit() 

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

파이썬 - twill을 이용한 web login & data scraping  (0) 2012.01.21
파이썬 - eval()  (0) 2012.01.20
파이썬 - find() vs index()/count()  (0) 2012.01.20
파이썬 - An Introduction to Python Lists  (0) 2012.01.20
파이썬 vs 루비  (0) 2012.01.17