2016-09-22 6 views
1

내가 원하는 것보다 다르게 포맷 된 파일을 통과하는 코드 조각에서 나는 엄청난 속도 저하를 경험합니다.파일 래핑을위한 팁

약 1000 개의 줄이있는 500 개의 파일을 처리하는 속도가 2 시간 정도입니다. 나는 왜 그렇게 많은 시간을 할애해야하는지, 그래서 느린 이유와 빨리 만드는 법에 대한 의견을 환영합니다. 여기 내 코드는 다음과 같습니다.

f는 파일 찾기에 대한 정보가있는 배열입니다.

def athwrap(athfpath, savefpath, fdirection): 
    ath = [] 
    with open(athfpath, 'r') as file: 
     for j, line in enumerate(file): 
      if j == 6: 
       npts = int(line[5:12]) 
       dt = float(line[17:25]) 
       ath = np.array((fdirection, npts, dt)) 
      elif j > 6: 
       uys = [float(n) for n in line.split()] 
       ath = np.hstack((ath, uys)) 
       if not os.path.isdir(savefpath): 
        os.makedirs(savefpath, exist_ok=True) 
       np.savetxt(savefpath + f[i, 15] + '.txt', ath, fmt='%s') 
    file.close() 

# Search and Wrap Files 
k = 1 
for i in range(0, len(f)): 
    athpath = path + f[i, 16] + '/' + f[i, 15] + '.ATH' 
    savepath = savpath + f[i, 16] + '/' 
    if os.path.isfile(athpath): 
     if k % 3 == 0: 
      direction = "Y" 
      athwrap(athpath, savepath, direction) 
     elif k % 2 == 0: 
      direction = "X" 
      athwrap(athpath, savepath, direction) 
     else: 
      direction = "Z" 
      athwrap(athpath, savepath, direction) 
    else: 
     print("Could find file " + loc + '/' + site + '/' + f[i, 16] + '/' + f[i, 15]) 
    k += 1 
+0

'np.savetxt' 행이 의도 한대로 작동합니까? 그것은 'athwrap' 함수에서 동일한 파일을 반복적으로 덮어 쓰는 것처럼 보입니다. 왜냐하면'i'는 입력 파일의 루프 동안 변경되지 않기 때문입니다. 한 번 쓰려고한다면'for'와 같은 수준으로 그 줄을 들여 쓰기를 원할 것입니다. 각 줄을 다른 파일에 쓰고 싶다면,'f'의 룩업에서'j'를 사용하고 싶을 것입니다 (그리고 아마'hstack' 비트를 다르게 할 것입니다, 확실하지 않습니다). – Blckknght

+0

파일 핸들을 여는'with' 문 다음에 파일 핸들을 닫을 필요도 없습니다 (또한 할 수 있습니다). 자동으로 닫힙니다. – chepner

+0

이 질문의 제목과 텍스트 사이에 명백한 연관성이 거의 없습니다. 실제로 열거 된 성능 오버 헤드가 얼마나 실망 스럽 겠는가를 실제로 알고 자하는 사람이 있습니다. 확실히 미래의 독자들에게 이것이 더 유용하게 쓰일 수있는 더 좋은 책을 찾을 수 있을까요? –

답변

0

들여 쓰기는 생명의 은인이었습니다!

def athwrap(athfpath, savefpath, fdirection): 
    ath = [] 
    with open(athfpath, 'r') as file: 
     for j, line in enumerate(file): 
      if j == 6: 
       npts = int(line[5:12]) 
       dt = float(line[17:25]) 
       ath = np.array((fdirection, npts, dt)) 
      elif j > 6: 
       uys = [float(n) for n in line.split()] 
       ath = np.hstack((ath, uys)) 
    if not os.path.isdir(savefpath): 
     os.makedirs(savefpath, exist_ok=True) 
    np.savetxt(savefpath + f[i, 15] + '.txt', ath, fmt='%s') 
+1

왜'file.close()'인가? 'with open (...) as file : '의 전체적인 점은 블록을 빠져 나오면 자동으로 닫기를 실행한다는 것입니다. –

+0

수정 됨 고마워요! –

2

현재 사용중인 행을 확인하지 마십시오. 이를 코드 구조에 구현하십시오. 당신이 savefpath을 제거하는 외부 사람을 기대하지 않는 또한

def athwrap(athfpath, savefpath, fdirection): 
    ath = [] 
    with open(athfpath, 'r') as file: 
     # Ignore the first 6 lines, and keep the 7th 
     for __ in range(7): 
      line = next(file) 

     nets = int(line[5:12]) 
     dt = float(line[17:25]) 
     ath = np.array((fdirection, npts, dt)) 

     # For the rest of the lines 
     for line in file: 
      uys = [float(n) for n in line.split()] 
      ath = np.hstack((ath, uys)) 
      if not os.path.isdir(savefpath): 
       os.makedirs(savefpath, exist_ok=True) 
      np.savetxt(savefpath + f[i, 15] + '.txt', ath, fmt='%s') 

는 반복적으로 존재를 확인 할 필요가 없습니다. 누군가 을 제거하면, 작성한 후에도 쓰기를 시도하기 전에 그렇게 할 가능성이 높습니다. 수정해야 할이 질문의 범위를 벗어나는 경쟁 조건이 있습니다. 함수의 맨 위에 한 번만 확인하고 필요한 경우이 함수를 만듭니다.