IT

ipython 노트북에서 셀 실행 시간을 측정하는 간단한 방법

lottoking 2020. 6. 23. 07:03
반응형

ipython 노트북에서 셀 실행 시간을 측정하는 간단한 방법


셀의 원래 출력 외에도 셀 실행에 소요되는 시간을 얻고 싶습니다.

이를 위해 시도 %%timeit -r1 -n1했지만 셀 내에 정의 된 변수를 노출하지 않습니다.

%%time 하나의 문장 만 포함하는 셀에서 작동합니다.

In[1]: %%time
       1
CPU times: user 4 µs, sys: 0 ns, total: 4 µs
Wall time: 5.96 µs
Out[1]: 1

In[2]: %%time
       # Notice there is no out result in this case.
       x = 1
       x
CPU times: user 3 µs, sys: 0 ns, total: 3 µs
Wall time: 5.96 µs

가장 좋은 방법은 무엇입니까?

최신 정보

나는 지금 꽤 오랫동안 Nbextension에서 Execute Time을 사용하고 있습니다. 훌륭합니다.


Phillip Cloud의 github에서 cell magic 및이 프로젝트를 사용하십시오.

항상 기본적으로로드하려는 경우 노트북 상단에 이것을 넣거나 구성 파일에 넣으십시오.

%install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime

로드되면, 후속 셀 실행의 모든 ​​출력에는 실행에 소요 된 시간 (분 및 초)이 포함됩니다.


이 문제를 극복하는 유일한 방법은 print로 마지막 문장을 실행하는 것입니다.

셀 매직은로 시작 %%하고 라인 매직은로 시작 한다는 것을 잊지 마십시오% .

%%time
clf = tree.DecisionTreeRegressor().fit(X_train, y_train)
res = clf.predict(X_test)
print(res)

셀 내부에서 수행 된 모든 변경 사항은 다음 셀에서 고려되지 않습니다. 파이프 라인이있을 때는 직관적이지 않습니다. 예


%time그리고 %timeit이제 와서 ipython의 일부 기능이 내장되어있어 마법 명령


더 쉬운 방법은 jupyter_contrib_nbextensions 패키지에서 ExecuteTime 플러그인을 사용하는 것입니다.

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime

나는 단순히 %%time세포의 시작 부분에 추가 하고 시간을 얻었다. Jupyter Spark 클러스터 / 가상 환경에서도 동일하게 사용할 수 있습니다. %%time셀 상단에 추가 하면 출력이 나타납니다. Jupyter를 사용하는 스파크 클러스터에서 셀 상단에 추가하고 다음과 같이 출력했습니다.

[1]  %%time
     import pandas as pd
     from pyspark.ml import Pipeline
     from pyspark.ml.classification import LogisticRegression
     import numpy as np
     .... code ....

Output :-

CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s

때때로 셀에서 서식이 다른 경우 print(res), but jupyter/ipython comes with a display. See an example of the formatting difference using pandas below.

%%time
import pandas as pd 
from IPython.display import display

df = pd.DataFrame({"col0":{"a":0,"b":0}
              ,"col1":{"a":1,"b":1}
              ,"col2":{"a":2,"b":2}
             })

#compare the following
print(df)
display(df)

그만큼 display statement can preserve the formatting. 스크린 샷


This is not exactly beautiful but without extra software

class timeit():
    from datetime import datetime
    def __enter__(self):
        self.tic = self.datetime.now()
    def __exit__(self, *args, **kwargs):
        print('runtime: {}'.format(self.datetime.now() - self.tic))

그런 다음 다음과 같이 실행할 수 있습니다.

with timeit():
    # your code, e.g., 
    print(sum(range(int(1e7))))

% 49999995000000
% runtime: 0:00:00.338492

당신이 사용할 수있는 timeit magic function for that.

%timeit CODE_LINE

아니면 세포에

%%timeit 

SOME_CELL_CODE

https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb 에서 더 많은 IPython 매직 기능 확인


import time
start = time.time()
"the code you want to test stays here"
end = time.time()
print(end - start)

파이썬의 프로파일 링 마술 명령을보고 싶을 수도 있습니다. %prunwhich gives something like -

def sum_of_lists(N):
    total = 0
    for i in range(5):
        L = [j ^ (j >> i) for j in range(N)]
        total += sum(L)
    return total

그때

%prun sum_of_lists(1000000)

돌아올 것이다

14 function calls in 0.714 seconds  

Ordered by: internal time      

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
    5    0.599    0.120    0.599    0.120 <ipython-input-19>:4(<listcomp>)
    5    0.064    0.013    0.064    0.013 {built-in method sum}
    1    0.036    0.036    0.699    0.699 <ipython-input-19>:1(sum_of_lists)
    1    0.014    0.014    0.714    0.714 <string>:1(<module>)
    1    0.000    0.000    0.714    0.714 {built-in method exec}

I find it useful when working with large chunks of code.


When in trouble what means what:

?%timeit 또는 ??timeit

세부 사항을 얻으려면 다음을 수행하십시오.

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

Time execution of a Python statement or expression using the timeit
module.  This function can be used both as a line and cell magic:

- In line mode you can time a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not timed) and the body of the cell is timed.  The cell
  body has access to any variables created in the setup code.

참고 URL : https://stackoverflow.com/questions/32565829/simple-way-to-measure-cell-execution-time-in-ipython-notebook

반응형