programing

Matlab의 tic 및 toc 함수에 해당하는 파이썬은 무엇입니까?

lovejava 2023. 7. 18. 21:23

Matlab의 tic 및 toc 함수에 해당하는 파이썬은 무엇입니까?

Matlab의 tictoc 함수에 해당하는 파이썬은 무엇입니까?

▁▁apart을외.timeit를 가져온 후)입니다.time):

t = time.time()
# do stuff
elapsed = time.time() - t

사용하고 싶은 도우미 클래스가 있습니다.

class Timer(object):
    def __init__(self, name=None):
        self.name = name

    def __enter__(self):
        self.tstart = time.time()

    def __exit__(self, type, value, traceback):
        if self.name:
            print('[%s]' % self.name,)
        print('Elapsed: %s' % (time.time() - self.tstart))

컨텍스트 관리자로 사용할 수 있습니다.

with Timer('foo_stuff'):
   # do some foo
   # do some stuff

때때로 나는 이 기술이 더 편리하다고 생각합니다.timeit모든 것은 당신이 측정하고자 하는 것에 달려 있습니다.

Matlab에서 python으로 마이그레이션할 때도 같은 질문이 있었습니다.이 스레드의 도움으로 저는 Matlab의 정확한 아날로그를 만들 수 있었습니다.tic()그리고.toc()만 하면 .스크립트 맨 위에 다음 코드를 삽입하기만 하면 됩니다.

import time

def TicTocGenerator():
    # Generator that returns time differences
    ti = 0           # initial time
    tf = time.time() # final time
    while True:
        ti = tf
        tf = time.time()
        yield tf-ti # returns the time difference

TicToc = TicTocGenerator() # create an instance of the TicTocGen generator

# This will be the main function through which we define both tic() and toc()
def toc(tempBool=True):
    # Prints the time difference yielded by generator instance TicToc
    tempTimeInterval = next(TicToc)
    if tempBool:
        print( "Elapsed time: %f seconds.\n" %tempTimeInterval )

def tic():
    # Records a time in TicToc, marks the beginning of a time interval
    toc(False)

바로 그거야!이제 완전히 사용할 준비가 되었습니다.tic()그리고.toc()매트랩입니다.를 들어, .

tic()

time.sleep(5)

toc() # returns "Elapsed time: 5.00 seconds."

사실, 이것은 내장된 Matlab 기능보다 더 다용도입니다.여서다인생수있다습니성할를스의 수 .TicTocGenerator여러 작업을 추적하거나 시간을 다르게 지정할 수 있습니다.예를 들어 스크립트의 타이밍을 지정하는 동안 스크립트의 각 부분과 전체 스크립트의 타이밍을 개별적으로 지정할 수 있습니다.(구체적인 예를 제시하겠습니다)

TicToc2 = TicTocGenerator() # create another instance of the TicTocGen generator

def toc2(tempBool=True):
    # Prints the time difference yielded by generator instance TicToc2
    tempTimeInterval = next(TicToc2)
    if tempBool:
    print( "Elapsed time 2: %f seconds.\n" %tempTimeInterval )

def tic2():
    # Records a time in TicToc2, marks the beginning of a time interval
    toc2(False)

이제 두 가지 사항에 대해 시간을 지정할 수 있습니다.다음 예제에서는 스크립트의 전체 시간과 일부 시간을 개별적으로 지정합니다.

tic()

time.sleep(5)

tic2()

time.sleep(3)

toc2() # returns "Elapsed time 2: 5.00 seconds."

toc() # returns "Elapsed time: 8.00 seconds."

사실, 당신은 심지어 사용할 필요도 없습니다.tic()매번.시간을 지정할 일련의 명령이 있으면 다음과 같이 기록할 수 있습니다.

tic()

time.sleep(1)

toc() # returns "Elapsed time: 1.00 seconds."

time.sleep(2)

toc() # returns "Elapsed time: 2.00 seconds."

time.sleep(3)

toc() # returns "Elapsed time: 3.00 seconds."

# and so on...

이것이 도움이 되길 바랍니다.

가장 좋은 아날로그 토픽과 토크는 단순히 파이썬으로 정의하는 것입니다.

def tic():
    #Homemade version of matlab tic and toc functions
    import time
    global startTime_for_tictoc
    startTime_for_tictoc = time.time()

def toc():
    import time
    if 'startTime_for_tictoc' in globals():
        print "Elapsed time is " + str(time.time() - startTime_for_tictoc) + " seconds."
    else:
        print "Toc: start time not set"

그런 다음 다음과 같이 사용할 수 있습니다.

tic()
# do stuff
toc()

통보, 나는 파이썬의 통보.%time,%timeit,%prun그리고.%lprun 있다면 (있다면)line_profiler(설치됨) 프로파일링 요구를 상당히 잘 충족시킵니다. 단, 다에대사사의 tic-toc-like 기능은 GUI에서 사용자의 마우스 움직임에 의해 상호작용적으로 구동되는 계산을 프로파일링하려고 할 때 발생했습니다.스팸메일을 보내고 싶었습니다.tic모래땅toc소스에 s를 입력하는 동시에 대화형 테스트를 수행하는 것이 병목 현상을 가장 빠르게 드러낼 수 있는 방법입니다.일라이 벤더스키의 집에 갔습니다.Timer클래스, 하지만 완전히 행복하지는 않았습니다. 왜냐하면 그것은 제가 코드의 들여쓰기를 변경해야 했기 때문입니다. 이것은 일부 편집자들에게 불편할 수 있고 버전 관리 시스템을 혼란시킬 수 있습니다.또한, 다른 기능의 포인트 사이의 시간을 측정할 필요가 있을 수 있으며, 이는 다음과 같이 작동하지 않습니다.with해 본 결과 과 같습니다.Python의 영리함을 많이 시도해 본 결과 가장 잘 작동하는 간단한 솔루션은 다음과 같습니다.

from time import time
_tstart_stack = []

def tic():
    _tstart_stack.append(time())

def toc(fmt="Elapsed: %s s"):
    print fmt % (time() - _tstart_stack.pop())

이것은 스택의 시작 시간을 밀어넣는 방식으로 작동하므로 여러 수준에서 올바르게 작동합니다.tic모래땅toc의 형식 할 수 .toc추가 정보를 표시하기 위한 진술, 나는 일라이의 것에 대해 좋아했다.Timer학생들

어떤 이유에서인지 순수 Python 구현의 오버헤드가 걱정되어 C 확장 모듈도 테스트했습니다.

#include <Python.h>
#include <mach/mach_time.h>
#define MAXDEPTH 100

uint64_t start[MAXDEPTH];
int lvl=0;

static PyObject* tic(PyObject *self, PyObject *args) {
    start[lvl++] = mach_absolute_time();
    Py_RETURN_NONE;
}

static PyObject* toc(PyObject *self, PyObject *args) {
return PyFloat_FromDouble(
        (double)(mach_absolute_time() - start[--lvl]) / 1000000000L);
}

static PyObject* res(PyObject *self, PyObject *args) {
    return tic(NULL, NULL), toc(NULL, NULL);
}

static PyMethodDef methods[] = {
    {"tic", tic, METH_NOARGS, "Start timer"},
    {"toc", toc, METH_NOARGS, "Stop timer"},
    {"res", res, METH_NOARGS, "Test timer resolution"},
    {NULL, NULL, 0, NULL}
};

PyMODINIT_FUNC
inittictoc(void) {
    Py_InitModule("tictoc", methods);
}

'MacOSX', 'MacOSX', 'MacOSX'인지 했습니다.lvl간결성의 범위를 벗어났습니다.하는 동안에tictoc.res()시스템에서 약 50나노초의 해상도를 제공하며, Python 문을 측정하는 지터가 마이크로초 범위에 쉽게 있다는 것을 발견했습니다(그리고 IPython에서 사용할 경우 훨씬 더 많습니다).이 시점에서 Python 구현의 오버헤드는 무시할 수 있으므로 C 구현과 동일한 신뢰성으로 사용할 수 있습니다.

는 나는그유발견다니습했을용성의 을 발견했습니다.tic-toc되어 있습니다 -code_1은 10마이크로초 이상의 시간이 소요됩니다.와 같은 전략입니다.timeit정확한 측정을 위해 필요합니다.

사용할 수 있습니다.tic그리고.tocttictoc 함께 합니다.

pip install ttictoc

그리고 다음과 같이 스크립트에 가져오기만 하면 됩니다.

from ttictoc import tic,toc
tic()
# Some code
print(toc())

저는 방금 Matlab이 수행하는 중첩 틱톡을 달성하기 위한 모듈 [tictoc.py ]을 만들었습니다.

from time import time

tics = []

def tic():
    tics.append(time())

def toc():
    if len(tics)==0:
        return None
    else:
        return time()-tics.pop()

다음과 같은 방식으로 작동합니다.

from tictoc import tic, toc

# This keeps track of the whole process
tic()

# Timing a small portion of code (maybe a loop)
tic()

# -- Nested code here --

# End
toc()  # This returns the elapse time (in seconds) since the last invocation of tic()
toc()  # This does the same for the first tic()

도움이 되길 바랍니다.

모듈을 살펴봅니다.이것은 실제로 동등한 것은 아니지만, 만약 당신이 시간을 보내고 싶은 코드가 함수 안에 있다면 당신은 그것을 쉽게 사용할 수 있습니다.

pip install easy-tictoc

코드에서:

from tictoc import tic, toc

tic()

#Some code

toc()

고지 사항:저는 이 도서관의 저자입니다.

스테판과 반티모의 대답을 바탕으로, 저는 결국,

def Tictoc():
    start_stack = []
    start_named = {}

    def tic(name=None):
        if name is None:
            start_stack.append(time())
        else:
            start_named[name] = time()

    def toc(name=None):
        if name is None:
            start = start_stack.pop()
        else:
            start = start_named.pop(name)
        elapsed = time() - start
        return elapsed
    return tic, toc

순식간에utils.py모듈, 그리고 저는 그것을 사용합니다.

from utils import Tictoc
tic, toc = Tictoc()

이쪽입니다.

  • 간단히 사용할 수 있습니다.tic(),toc() 를 틀게 .
  • 이름을 할 수 .tic(1),toc(1)또는tic('very-important-block'),toc('very-important-block')
  • 이러한 방식으로 가져오기를 수행하면 이를 사용하는 모듈 간의 간섭을 방지할 수 있습니다.

(여기서 toc은 경과시간을 출력하지 않고 반환합니다.

파이썬 3에 대한 일라이의 답변 업데이트:

class Timer(object):
    def __init__(self, name=None, filename=None):
        self.name = name
        self.filename = filename

    def __enter__(self):
        self.tstart = time.time()

    def __exit__(self, type, value, traceback):
        message = 'Elapsed: %.2f seconds' % (time.time() - self.tstart)
        if self.name:
            message = '[%s] ' % self.name + message
        print(message)
        if self.filename:
            with open(self.filename,'a') as file:
                print(str(datetime.datetime.now())+": ",message,file=file)

Eli와 마찬가지로 컨텍스트 관리자로 사용할 수 있습니다.

import time 
with Timer('Count'):
    for i in range(0,10_000_000):
        pass

출력:

[Count] Elapsed: 0.27 seconds

또한 보고된 시간 단위(초)를 인쇄하고 Can이 제안한 대로 자릿수를 자르기 위해 업데이트했으며 로그 파일에도 추가할 수 있는 옵션이 있습니다.로깅 기능을 사용하려면 날짜 시간을 가져와야 합니다.

import time
import datetime 
with Timer('Count', 'log.txt'):    
    for i in range(0,10_000_000):
        pass

이 작업은 래퍼를 사용하여 수행할 수도 있습니다.시간을 맞추는 아주 일반적인 방법입니다.

이 예제 코드의 래퍼는 함수를 래핑하고 함수를 실행하는 데 필요한 시간을 출력합니다.

def timethis(f):
    import time

    def wrapped(*args, **kwargs):
        start = time.time()
        r = f(*args, **kwargs)
        print "Executing {0} took {1} seconds".format(f.func_name,  time.time()-start)
        return r
    return wrapped

@timethis
def thistakestime():
    for x in range(10000000):
        pass

thistakestime()

가 @Bendersky의 을 cctor를 @Eli Bendersky의 답변을 .__init__() dtor 그고리dtor__del__()원래 코드를 들여놓지 않고 보다 편리하게 사용할 수 있도록 타이밍을 조정합니다.

class Timer(object):
    def __init__(self, name=None):
        self.name = name
        self.tstart = time.time()

    def __del__(self):
        if self.name:
            print '%s elapsed: %.2fs' % (self.name, time.time() - self.tstart)
        else:
            print 'Elapsed: %.2fs' % (time.time() - self.tstart)

사용하려면 타이머("blahblah")를 일부 로컬 범위의 시작 부분에 간단히 입력합니다.경과 시간은 스코프 끝에 인쇄됩니다.

for i in xrange(5):
    timer = Timer("eigh()")
    x = numpy.random.random((4000,4000));
    x = (x+x.T)/2
    numpy.linalg.eigh(x)
    print i+1
timer = None

출력:

1
eigh() elapsed: 10.13s
2
eigh() elapsed: 9.74s
3
eigh() elapsed: 10.70s
4
eigh() elapsed: 10.25s
5
eigh() elapsed: 11.28s

이 솔루션은 프로파일링 요구사항에 적합합니다.

from time import time
import inspect

def tic():
    tic.t = time()

def toc(message=None):
    time_elapsed = time() - tic.t
    if message is None:
        message = inspect.currentframe().f_back.f_lineno
    print(message, time_elapsed)
    tic.t = time()
    return time_elapsed

그러면 그냥 많이 붙여주시면 됩니다.toc()당신 코드에 s, 그리고 당신은 꽤 강력한 프로파일러를 가지고 있습니다.(파일에서 발신자의 코드 행으로 기본 설정됨)

@Maxim의 답변을 기반으로 한 단순화된 솔루션은 다음과 같습니다.

def tictoc():
    """Python implementation of MATLAB tic-toc functionality."""
    from time import perf_counter_ns
    hashmap = {}
    def tic(key: str=None) -> None:
        """named tic method"""
        hashmap[key] = perf_counter_ns()
        return None
    def toc(key: str=None) -> float:
        """named toc method"""
        initial_ns = hashmap[key]
        current_ns = perf_counter_ns()
        elapsed_ns = current_ns - initial_ns
        elapsed_s  = elapsed_ns / (10**9)  # convert ns to s
        print(f"Elapsed time is {elapsed_s} seconds.")
        return elapsed_s  
    return tic, toc

파저있장가다다정니합고일라는 되어 있다고 합니다.utils.py다음과 같은 방식으로 사용됩니다.

from utils import tictoc

tic, toc = tictoc()

tic()
toc()
toc()
tic()
toc()

tic('foo')
toc('foo')
toc('foo')

toc()

원본과 달리 이 버전은 실행할 때 충돌하지 않습니다.toc() 번 합니다.tic키 값 타이머 기능을 유지합니다.또한 코드에서 불필요한 목록/배열 데이터 구조와 여러 조건부 분기를 제거하여 속도 저하를 유도합니다.해시 맵 조회 시간은 배열 크기 조정보다 빠른 O^1에서 일정합니다.또한, 저는 다음으로 전환했습니다.perf_counter_ns 타머, 반기를 .perf_counter그리고 그것에 의해 야기되는 정밀도 손실을 방지합니다.float활자를

더 낮은 레벨로 가고 싶은 사람이 있다면, 여기 Python C API를 사용하는 버전이 있습니다.

// tictoc.c
#define PY_SSIZE_T_CLEAN  // REQUIRED
#include <Python.h>       // Python C API

#include <stdint.h>       // uint64_t
#include <time.h>         // timespec
#include <sys/time.h>     // time types
#include <stdio.h>        // printf

typedef struct {
    uint64_t initial_ns;
    uint64_t current_ns;
    uint64_t elapsed_ns;
    double elapsed_s;
} timer;

timer t;

struct timespec ts;  // C11

// Unix POSIX clock time scaled to microseconds (us; 10^6 sec)
uint64_t posix_clock_time () {
    timespec_get(&ts, TIME_UTC);
    return ts.tv_sec * 1000000000 + ts.tv_nsec;  // ns = 10^-9 s
}

// tic
static PyObject* tic(PyObject* self, PyObject* args) {
    t.initial_ns = posix_clock_time();
    Py_RETURN_NONE;
}

// toc
static PyObject* toc(PyObject* self, PyObject* args) {
    t.current_ns = posix_clock_time();
    t.elapsed_ns = t.current_ns - t.initial_ns;
    t.elapsed_s  = (double)t.elapsed_ns / (double)1000000000.0;  // s = 10^9 ns
    printf("Elapsed time is %f seconds.\n", t.elapsed_s);
    return PyFloat_FromDouble(t.elapsed_s);
}

static PyMethodDef methods[] = {
    {"tic", tic, METH_NOARGS, "Start timer"},
    {"toc", toc, METH_NOARGS, "Stop timer"},
    {NULL, NULL, 0, NULL}
};

static struct PyModuleDef tictoc = {
    PyModuleDef_HEAD_INIT,
    "tictoc",    // name of module
    "A timer function analogous to MATLAB's tic-toc.",  // module documentation, may be NULL
    -1,          // size of per-interpreter state of module; -1 if module keeps state in global variables
    methods
};

PyMODINIT_FUNC PyInit_tictoc(void) {
    return PyModule_Create(&tictoc);
}

설다니합치께와 함께 합니다.setup.py파일 이름:

# setup.py
from distutils.core import setup, Extension

module1 = Extension(
    'tictoc',
    sources = ['tictoc.c']
)

setup(name = 'tictoc',
    version = '1.0',
    description = 'The tictoc package',
    ext_modules = [module1]
)

에서 를 합니다.python setup.py build이것MATLAB:MATLAB기본적하는 공유 됩니다.

from tictoc import tic, toc

tic()
toc()
toc()

tic()
toc()
toc()

언급URL : https://stackoverflow.com/questions/5849800/what-is-the-python-equivalent-of-matlabs-tic-and-toc-functions