科学の箱

科学・IT・登山の話題

Python

automated the boring – day8

投稿日:2018年2月28日 更新日:

https://automatetheboringstuff.com/chapter15/

さてプログラムを実行しているときに案外出てくる要件が時間計測。

例えばアルゴリズム間でパフォーマンスを比較するとか、経過時間に基づいてファイルをローテーションさせる。プログラムの開始時間と終了時間を記録するなどいろいろ考えられる。

pythonでもすでにtimeパッケージとして用意されているので使い方を確認する。


import time
def calcProd():
  # Calculate the product of the first 100,000 numbers.
  product = 1
  for i in range(1, 100000):
    product = product * i
  return product

startTime = time.time()
prod = calcProd()
endTime = time.time()
print('The result is %s digits long.' % (len(str(prod))))
print('Took %s seconds to calculate.' % (endTime - startTime))

こちらを実行すると以下のように時間が計測される。

$ python timex.py
The result is 456569 digits long.
Took 16.528652667999268 seconds to calculate.

次はsleep。これも重要である。入力と入力の間に一定の時間待ちを入れるとか、polling処理で受け付けているときにバッファを与えるとかいろいろな使い道がある。

<blockquote>> import time
>>> for i in range(3):
... print('tick')
... time.sleep(2)
... print('tock')
... time.sleep(2)
...
tick
tock
tick
tock
tick
tock</blockquote>

メタ情報

inarticle



メタ情報

inarticle



-Python
-

執筆者:


comment

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

関連記事

no image

連続データのビジュアル

Kaggle TitanicのFareを使っていくつかビジュアル 金額別ヒストグラム-1 titanic_df[‘Fare’].plot(kind=’hist’, figsize=(15,3),bin …

no image

kaggle Titanic Tutorial – 2

決定木を利用して分析する。 データの作成 y_train = d_train["Survived"].values x_train = d_train[["Pclass& …

no image

OpenCV

WindowsにOpenCVをインストールする場合に2つのやり方がある。 一つは様々な言語からOpenCVを利用できるようにする方法、2つ目の方法ではPythonからOpenCVを利用する方法である。 …

no image

kaggle Titanic Tutorial – 8

前回の結果がいまいちだった。これまではAgeは平均値でNullを埋めていた。平均値では明らか実際のデータと差異が出ると考えられる。そのためAgeがない情報についてより正確なAgeで補完するようにした。 …

no image

PythonでMicrosoft Visual C++ 14.0 is required エラーが出た場合

Visual Studio 2017だけでは不十分である。   https://visualstudio.microsoft.com/ja/downloads/から下記のリンク経由でBuil …

2018年2月
« 1月   3月 »
 1234
567891011
12131415161718
19202122232425
262728  

side bar top



アーカイブ

カテゴリー