2013-05-15 5 views
0

내 프로그램을 완료하는 데 걸리는 시간을 예상하는 방법이 필요합니다. 현재 중첩 된 for 루프에서 대부분의 시간을 보내고 있습니다. 이 for 루프 내에서 처리 된 출력 파일을 가져 오는 데 걸리는 시간을 알기 위해 얼마나 많은 반복이 발생했는지 알고 싶습니다. 파이썬에서 % done 파일을 출력하는 방법이 있습니까?파이썬의 파일로 출력 진행률 (백분율)

내 현재 접근 방식이지만 진행률 파일을 읽으려고하면 항상 비어 있습니다. 나는 파일을 닫음으로써 나는 무엇이 쓰여졌는지 알 수있을 것이라고 생각했다.

48  #Estimate finishing time 
49  progTotal = len(f1) 
50  prog = 0 
51 
52  #Now to calculate 1st order Walsh Coefficients by subtracting away 2nd order coefficients 
53  for g in f1: 
54   progFile = open("progress",'w') 
55   sumOfOtherWalsh = 0 
56   for gPair in w2: 
57    if g == gPair[0] or g == gPair[1]: 
58     sumOfOtherWalsh += w2.get(gPair, 0) #Add the walsh value into sum, if it is there 
59   f1[g] -= sumOfOtherWalsh #subtract all the Walsh values as well as the value in f1 
60   progFile.write(str(float(prog)/progTotal)+"\n") 
61   prog += 1 
62   progFile.close() 

놀랍게도 여기에서 정보를 찾을 수 없으므로 잘못하고 있다고 가정하지만 어쨌든 도움을 주셔서 감사합니다.

+1

이 왜 파일 내가 쓰기로 결정 않았다 STDOUT의 nstead? 쓰기 직전에 열어 본 후 바로 또는 100 회 반복 할 때마다 닫으십시오. 파이썬이 파일을 쓰는 동안 파일을 열려고 시도했을 수 있습니다. – placeybordeaux

+3

@ PeterMichealLacey-Bordeaux는 + 파일 (예 :'sys.stdout.flush()')에서'.flush()'를 자주 자주 호출 해보라고 말했습니다. 다른 작은 쓰기는 프로세스가 끝나기 전에 사용자가주의하지 않도록 충분히 오래 캐시됩니다. – 9000

답변

4

계산의 진행을 stdout으로 표시하는 경우 progressbar 모듈을 사용할 수 있습니다.

예 :

import time 
import progressbar 

maxval = 100 
pbar = progressbar.ProgressBar(maxval=maxval) 
pbar.start() 
for i in range(maxval): 
    # do something 
    time.sleep(0.05) 
    pbar.update(i+1) 
pbar.finish() 

출력 :

출력, 당신이 출력을 보게하는 파일을 닫습니다,하지만를 세척 할 필요는 없습니다 파일에 점점에 관해서는
$ python test.py 
52% |#####################################         | 

출력 버퍼. (사실 그것은 비효율적이고 열고 가능한 루프의 본문에 반복적으로 파일을 절단하는 아마 역효과 될 것입니다.)

file object's flush에서 모양과 디스크에 파일 내용을 플러싱에 대한 os module's fsync 방법 되세요. 그러나 이것은 일반적으로 요구되지 않아야합니다. 파일에 충분한 데이터를 쓸 때 버퍼는 터미널에 인쇄 할 수있는만큼 빠르게 플러시됩니다. (보통 tail -f progess_file을 문제없이 출력 할 수 있습니다.)

달성하고자하는 것이 로깅되어 있다면, logging module을보십시오. 당신은 좋은 확장 가능한 로깅 시스템을 얻기 위해 그것을 사용할 수 있습니다. 파일의 로깅을 수행할지 또는 코드의 단일 지점에서 표준 출력을 수행할지 여부를 선택할 수 있습니다. 당신은 이름이 바로 "getting"에 의해 동일한 로그 메인 로거를 다른 모듈의 로깅 활동을 첨부 할 수

logger = logging.getLogger("__main__") 

(또는, 당신은 아주 잘 거기에 다른 이름을 사용하여 다른 로거를 설정할 수 있습니다.)

예 :

import time 
import logging 

# set up the logging 
def setup_logger(logfilename = None): 
    logger = logging.getLogger(__name__) # probably __name__ == "__main__" 
    logger.setLevel(logging.DEBUG) 
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') 
    if logfilename: 
     # write to logfile 
     handler = logging.FileHandler(logfilename) 
    else: 
     # write to stdout 
     handler = logging.StreamHandler() 
    handler.setFormatter(formatter) 
    logger.addHandler(handler) 
    return logger 
logger = setup_logger("test.log") 

# example use of the logger 
maxval = 100 
for i in range(1,maxval+1): 
    # do something 
    time.sleep(0.05) 
    if (i)%(maxval/10) == 0: 
     logger.debug("progress:% 4d %% done", i) 

출력 :

2013-05-15 21:03:23,313 - DEBUG - progress: 10 % done 
2013-05-15 21:03:23,822 - DEBUG - progress: 20 % done 
2013-05-15 21:03:24,323 - DEBUG - progress: 30 % done 
2013-05-15 21:03:24,825 - DEBUG - progress: 40 % done 
2013-05-15 21:03:25,326 - DEBUG - progress: 50 % done 
2013-05-15 21:03:25,827 - DEBUG - progress: 60 % done 
2013-05-15 21:03:26,328 - DEBUG - progress: 70 % done 
2013-05-15 21:03:26,829 - DEBUG - progress: 80 % done 
2013-05-15 21:03:27,330 - DEBUG - progress: 90 % done 
2013-05-15 21:03:27,831 - DEBUG - progress: 100 % done