Development Tip

파이썬에서 단조로운 시간을 어떻게 얻습니까?

yourdevel 2021. 1. 10. 19:41
반응형

파이썬에서 단조로운 시간을 어떻게 얻습니까?


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

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 을 사용 합니다 .


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

파이썬에서 C 헤더에 올바른 상수 #defined를 이식하는 것은 까다 롭습니다. 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() 유용 할 수 있습니다.

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

참조 URL : https://stackoverflow.com/questions/1205722/how-do-i-get-monotonic-time-durations-in-python

반응형