【问题标题】:How do I run these simultaneously?我如何同时运行这些?
【发布时间】:2021-01-14 23:59:26
【问题描述】:

我对 Python 比较陌生,所以我不知道解决这个问题有多难或容易,但我正在尝试制作一个可以测量时间的函数,而不会在执行此操作时阻止其他代码执行。这是我所拥有的:

import time

def tick(secs):
    start = time.time()
    while True:
        end = time.time()
        elapsed = end - start
        if elapsed >= secs:
            return elapsed
            break


input("what time is it?: ")
print(f"one: {round(tick(1))}")
print(f"two: {round(tick(2))}")
print(f"three: {round(tick(3))}")
print(f"four: {round(tick(4))}")
print(f"five: {round(tick(5))}")

input 阻止计时器启动,直到它被输入,并且tick()'s after 不要同时运行。因此一次运行一个,例如 wait 1 seconds 然后 wait 2 seconds 而不是 wait 5 seconds (要清楚,我希望所有计时器与其他人同时开始运行,因此 5 秒计时器将与 1 秒计时器同时启动),感谢您抽出宝贵时间,如果您对此有解决方案,请告诉我。

【问题讨论】:

  • 你应该看看线程或多处理。

标签: python python-3.x


【解决方案1】:

不完全确定您要的是什么,但看起来如何:

import time
start=time.time()
input("what time is it?: ")

time.sleep(1)
print(time.time()-start)
time.sleep(2)
print(time.time()-start)
time.sleep(3)
print(time.time()-start)
time.sleep(4)
print(time.time()-start)
time.sleep(5)
print(time.time()-start)

【讨论】:

    【解决方案2】:

    tick 没有同时运行,因为您首先等待 1 秒,然后再次等待 2,然后再次等待 3,等等。

    做一个简单的事情是有一个你想“暂停”的时间间隔列表,在你的情况下是[1, 2, 3, 4, 5],它们是按数字排序的。然后,您将通过检查elapsed >= secs 来跟踪当前索引,如果成功,您将其加一。这里是一瞥

    import time
    
    def tick(tocks: list):
        """Tocks is a list of the time intervals which you want to be
           notified at when are reached, all of them are going to run in parallel.
        """
        tocks = sorted(tocks) 
        current = 0  # we are at index 0 which is the lowest interval
    
        start = time.time()
        while current < len(tocks): # while we have not reached the last interval
            end = time.time()
            elapsed = end - start
            if elapsed >= tocks[current]: # if the current interval has passed check for the next 
                print(f"Tock: {tocks[current]}")
                current += 1
    

    然后可以像这样调用这个函数

    tick([1, 2, 3, 4, 5])
    

    这将同时打印 1 到 5 秒。这是输出

    Tock: 1 # at 1 sec
    Tock: 2 # at 2 sec
    Tock: 3 # at 3 sec
    Tock: 4 # .....
    Tock: 5
    

    你可以想象,如果你选择像[0.5, 0.50001, 0.50002] 这样非常接近的数字,这可能会有一些小缺陷,并且因为差异很小,0.0001 秒可能实际上不会过去。

    您也可以尝试 multithreading,如前所述,但对于一些非常简单的事情,这将是一个非常占用 CPU 的任务(想象一下要数到 100 并且您必须打开 100 个线程)。

    【讨论】:

    • 谢谢!,这适用于等待,但我需要在后台运行的东西,例如运行此功能:tick([1, 2, 3, 4, 5]),但能够在任何地方使用input(),同时仍保持计数准确,因此 python 在打印 tocks 之前不会等待输入。
    • @RazerDemon 打印是您唯一想做的事情,还是您希望能够访问input() 中的当前时间间隔?如果您只想打印,您可以只为输入创建一个新线程,在另一种情况下(您希望能够访问)事情是困难的,而不是跨平台的,您可以看看 here 或 @987654322 @.
    • 打印只是为了查看值是否在正确的时间更新。我想用它作为一个计时器来更新可重置但也在后台更新的值,而不干扰其余代码的输出。就像为视频游戏中的技能设置冷却时间一样。
    猜你喜欢
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 2011-09-10
    • 1970-01-01
    • 2021-08-10
    相关资源
    最近更新 更多