Pythonで単調な時間を取得するにはどうすればよいですか?
-
05-07-2019 - |
質問
実際のウォールタイムで何かがかかった時間を記録したい。現在、私はこれをやっています:
startTime = time.time()
someSQLOrSomething()
print "That took %.3f seconds" % (time.time() - startTime)
ただし、SQLクエリ(またはそれが何であれ)の実行中に時間が調整されると、失敗します(誤った結果が生成されます)。
ベンチマークを行いたくありません。ライブシステムの傾向を確認するために、ライブアプリケーションにログを記録します。
clock_gettime(CLOCK_MONOTONIC、...)のようなものが欲しいのですが、Pythonで。また、できればclock_gettime()を呼び出すCモジュールを記述する必要はありません。
解決
この関数は、ctypesを使用してアクセスできるほど単純です:
#!/usr/bin/env python
__all__ = ["monotonic_time"]
import ctypes, os
CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
class timespec(ctypes.Structure):
_fields_ = [
('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long)
]
librt = ctypes.CDLL('librt.so.1', use_errno=True)
clock_gettime = librt.clock_gettime
clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
def monotonic_time():
t = timespec()
if clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
errno_ = ctypes.get_errno()
raise OSError(errno_, os.strerror(errno_))
return t.tv_sec + t.tv_nsec * 1e-9
if __name__ == "__main__":
print monotonic_time()
他のヒント
今、Python 3.3では time.monotonic を使用します。
この質問で指摘されているように、NTPを回避Linuxでの再調整にはCLOCK_MONOTONIC_RAWが必要です。 Linuxでは2.6と定義されています(2.6.28以降)。
PythonからCヘッダーで定義された正しい定数#portableを取得するのは難しいです。 h2pyがありますが、実行時に値を取得するのに実際には役立ちません。
Python 2.7で単調な時間を取得する方法は次のとおりです。
monotonic
パッケージをインストールします:
pip install monotonic
次にPythonで:
import monotonic; mtime = monotonic.time.time #now mtime() can be used in place of time.time()
t0 = mtime()
#...do something
elapsed = mtime()-t0 #gives correct elapsed time, even if system clock changed.
time.monotonic()
は役に立つかもしれません:
単調な時計、つまり逆戻りできない時計の値を(小数秒で)返します。クロックは、システムクロックの更新の影響を受けません。返される値の参照ポイントは未定義であるため、連続した呼び出しの結果の差のみが有効です。
所属していません StackOverflow