我的自定义类在每次迭代中都有很大的开销

问题描述

我有以下类 PeriodicTask ,其目的是在调用停止之前的时间间隔内调用函数(任务)。我们假设被调用的任务的运行时间比间隔时间短。所以使用这个自定义类,没有执行任务的开销。

import threading
from functools import partial
from threading import Event
from time import time,sleep


class LineTimer:
    """ One line,simple timer"""
    def __init__(self):
        self.start_time = None
        self.is_working = False

    def start(self):
        if not self.is_working:
            self.start_time = time()
            self.is_working = True
        else:
            print('Timer already working')

    def elapsed(self):
        if self.is_working:
            return time() - self.start_time
        else:
            print('Timer is not working')

    def stop(self):
        elapsed = self.elapsed()
        self.is_working = False
        self.start_time = None
        return elapsed


class PeriodicTask(threading.Thread):
    def __init__(self,func,interval,args=None):
        super().__init__()

        self.func = func if args is None else partial(func,args=args)
        self.interval = interval
        self.waiter_event = threading.Event()
        self.timer = LineTimer()

        self.state = 'init'
        self.wait_for_command = Event()

    def run(self):
        self.state = 'running'

        while True:
            self.waiter_event.clear()

            if self.state == 'running':
                self.timer.start()
                self.func()

            elif self.state == 'stopped':
                return

            self.waiter_event.wait(timeout=self.interval - self.timer.stop())

    def stop(self):
        self.state = 'stopped'
        self.waiter_event.set()

我在使用此类的短时间间隔(例如 0.1 秒)时遇到问题,其中我的开销为 ~0.01 秒(并且与间隔无关)。

运行以下代码:

def print_time_from_last_call():
    cur_time = print_time_from_last_call.cur_time
    new_time = time()
    print(new_time - cur_time)
    print_time_from_last_call.cur_time = new_time
print_time_from_last_call.cur_time = time()


dt = 0.1

t = PeriodicTask(print_time_from_last_call,dt)
t.start()
sleep(dt*10)
t.stop()

给我:

0.0010004043579101562
0.11499905586242676
0.11100196838378906
0.10899806022644043
0.1100008487701416
0.10699725151062012
0.1119847297668457
0.1093902587890625
0.10859394073486328
0.10991382598876953

您认为是什么导致了这种开销?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)