Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从python计时器中检索剩余时间_Python_Timer_Python Multithreading_Elapsedtime - Fatal编程技术网

从python计时器中检索剩余时间

从python计时器中检索剩余时间,python,timer,python-multithreading,elapsedtime,Python,Timer,Python Multithreading,Elapsedtime,寻找从python计时器获取剩余时间和已用时间的简单方法。当前有(基于用于threading.Timer和上一篇文章的github源代码): 这看起来是否合理有效(不需要超过线程。计时器当前提供的精度)?性能计数器() 性能计数器()的优点: perf_counter()将提供比time.clock()函数更精确的值 从Python3.8time.clock()函数将被删除,并将使用perf_counter 我们可以计算float和integer两个时间值,以秒和纳秒为单位 性能计数器() 性能

寻找从python计时器获取剩余时间和已用时间的简单方法。当前有(基于用于threading.Timer和上一篇文章的github源代码):

这看起来是否合理有效(不需要超过线程。计时器当前提供的精度)?

性能计数器()

性能计数器()的优点:

  • perf_counter()
    将提供比
    time.clock()函数更精确的值

  • 从Python3.8
    time.clock()
    函数将被删除,并将使用
    perf_counter

  • 我们可以计算float和integer两个时间值,以秒和纳秒为单位

  • 性能计数器()

    性能计数器()的优点:

  • perf_counter()
    将提供比
    time.clock()函数更精确的值

  • 从Python3.8
    time.clock()
    函数将被删除,并将使用
    perf_counter

  • 我们可以计算float和integer两个时间值,以秒和纳秒为单位


  • 是的,这是一个很好的方法。这完全取决于你的需要。通常,如果我想通过程序监控时间,我只需使用
    time.time()
    函数。是的,这是一种很好的方法。这完全取决于你的需要。一般来说,如果我想通过我的程序监控时间,我只需使用
    time.time()
    函数。谢谢,这很简单,而且会提供更高的精度。使用这种方法是因为类方法对我来说是过度的,正如@xaander1提到的,解决方案提供了额外的解决方案。再次感谢!谢谢,这很简单,可以提供更高的精度。我选择这种方法,因为类方法对我来说太过分了,正如@xaander1所提到的,解决方案提供了额外的解决方案。再次感谢!
    import threading
    import time
    
    class CountdownTimer(threading.Thread):
        def __init__(self, interval, function, args=None, kwargs=None):
            threading.Thread.__init__(self)
            self.interval = interval
            self.function = function
            self.args = args if args is not None else []
            self.kwargs = kwargs if kwargs is not None else {}
            self.finished = Event()
            self.started_at = None
    
        def cancel(self):
            self.finished.set()
    
        def elapsed(self):
            return time.time() - self.started_at
    
        def remaining(self):
            return self.interval - self.elapsed()
    
        def run(self):
            self.started_at = time.time()
            self.finished.wait(self.interval)
            if not self.finished.is_set():
                self.function(*self.args, **self.kwargs)
            self.finished.set()
    
    import time
    
    start = time.perf_counter()
    time.sleep(2)
    finish = time.perf_counter()
    print(f'Finished in {round(finish-start, 2)} second(s)')