문제

실시간 벽에 걸리는 시간을 기록하고 싶습니다. 현재 나는 이것을하고있다 :

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에서는 사용할 것입니다 시간. 모노 닉.

지적한대로 이 질문, Linux에서 NTP 재조정을 피하려면 Clock_Monotonic_Raw가 필요합니다. Linux에서 4로 정의됩니다 (2.6.28 이후).

Python의 C 헤더에서 정의 된 올바른 상수를 포장적으로 얻는 것은 까다 롭습니다. H2Py가 있지만 실제로 런타임에 값을 얻는 데 도움이되지 않습니다.

Python 2.7에서 단조로운 시간을 얻는 방법은 다음과 같습니다.

설치 monotonic 패키지:

pip install monotonic

그런 다음 파이썬에서 :

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() 유용 할 수 있습니다 :

단조 시계의 값 (분수 초)을 반환합니다. 즉, 뒤로 갈 수없는 시계입니다. 시계는 시스템 시계 업데이트의 영향을받지 않습니다. 반환 된 값의 기준점은 정의되지 않으므로 연속 호출 결과의 차이 만 유효합니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top