意見交換
Raspbian Jessieでpython3.4.2を使用しています。
タイムアウト秒経過したら処理を抜けるプログラムを書いています。
python
1import time 2 3elapsed_sec = 0.0 4pre_time = time.perf_counter() 5 6while elapsed_sec <= timeout_sec: 7 (処理) 8 now_time = time.perf_counter() 9 elapsed_sec += now_time - pre_time 10 pre_time = now_time
このプログラムは、time.perf_counter()がオーバーフローしたら意図しない動作をしてしまいます。
time.perf_counter()の最大値を知りたい(というか、とりうる値の範囲を知りたい)のですが、どうすればいいでしょうか?
[追記1]
回答より、想像以上に早くオーバーフローしそうだということで、1分ごとのtime.perf_counter()の値をperf_counter.historyファイルに保存するコードを書きました。
python
1#-*- coding:utf-8 -*- 2import time 3import datetime 4 5while 1: 6 time.sleep(60) 7 d = datetime.datetime.now() 8 timestamp = "{}:{}:{}".format(d.hour, d.minute, d.second) 9 perf_c = str( time.perf_counter() ) 10 text = "[{}]{}\r\n".format(timestamp, perf_c) 11 12 f = open("/var/tmp/perf_counter.history", "a") 13 f.write( text ) 14 f.close()
↓perf_counter.history
[17:19:6]5345.205548377 [17:20:6]5405.256627527 [17:21:6]5465.262088711 [17:22:6]5525.313487511 ... (略) ... [8:40:40]60639.65602925 [8:41:40]60699.664641323 [8:42:40]60759.669727713
ファイルを眺めた所、オーバーフローはしていませんでした。
そもそもtime.perf_counter()の型は何?と思い調べた所、float型でした。
>>> import time >>> type( time.perf_counter() ) <class 'float'>
float型ということは、オーバーフローした後はマイナスの値を取る可能性があります。
ここで、pythonのfloat型の範囲がわからなかったので調べた所、次のサイトにヒントが書いてありました。
文系のための「数値型」(2)
さて、次に実際の「有効桁数」と「精度」について見てみる。
Python の数値型は、C言語の数値型を借用していることはすでに述べた。
では、C言語のどの型を借用しているのか?
int ← C言語のlong型
long ← C言語には無い?
float ← C言語におけるdouble型
なんと、C言語のデータ型の大きい方だけを使っているようである。
pythonのfloat型はどうやらdouble型だそうです。
混乱してきたので整理すると、
time.perf_counter()は
・float型の数値を返す
・pythonのfloat型はC言語のdouble型に当たる
・ということは、値の範囲は-2^308~2^308(間違ってたらすみません)
time.perf_counter()のオーバーフロー後の動作が気になりますが、とりあえず「タイムアウト秒経過したら処理を抜ける」コードは次のように変更することで問題を回避できそうです。
python
1import time 2 3elapsed_sec = 0.0 4pre_time = time.perf_counter() 5 6while elapsed_sec <= timeout_sec: 7 (処理) 8 now_time = time.perf_counter() 9 if now_time > pre_time: 10 elapsed_sec += now_time - pre_time 11 pre_time = now_time
回答1件
あなたの回答
tips
プレビュー
下記のような回答は推奨されていません。
このような回答には修正を依頼しましょう。
2017/02/15 07:42
2017/02/16 01:35