秒表在Python中

时间:2011-05-04 21:53:24

标签: python time

我正在尝试创建一个简单的游戏,其中的重点是在一定的时间内收集尽可能多的块,比如10秒。如何让秒表在程序开始时开始计时,当它达到10秒时,做一些事情(在这种情况下,退出循环)?

10 个答案:

答案 0 :(得分:38)

import time

now = time.time()
future = now + 10
while time.time() < future:
    # do stuff
    pass

或者,如果你已经有了循环:

while True:
    if time.time() > future:
        break
    # do other stuff

这种方法适用于pygame,因为它几乎要求你有一个很大的主循环。

答案 1 :(得分:5)

如果系统时间发生变化(用户更改时间,可以通过NTP等时间调整服务或从/到天数节省时间更正),使用time.time()/ datetime.datetime.now()将会中断!)。

time.monotonic()或time.perf_counter()似乎是正确的方法,但它们只能从python 3.3中获得。另一种可能性是使用threading.Timer。这是否比time.time()和朋友更可靠取决于内部实现。另请注意,在系统资源方面创建新线程并不是完全免费的,因此在需要并行运行大量计时器的情况下,这可能是一个糟糕的选择。

答案 2 :(得分:4)

我在python程序中使用此函数。该功能的输入例如:
    value = time.time()

def stopWatch(value):
    '''From seconds to Days;Hours:Minutes;Seconds'''

    valueD = (((value/365)/24)/60)
    Days = int (valueD)

    valueH = (valueD-Days)*365
    Hours = int(valueH)

    valueM = (valueH - Hours)*24
    Minutes = int(valueM)

    valueS = (valueM - Minutes)*60
    Seconds = int(valueS)


    print Days,";",Hours,":",Minutes,";",Seconds




start = time.time() # What in other posts is described is

***your code HERE***

end = time.time()         
stopWatch(end-start) #Use then my code

答案 3 :(得分:3)

threading.Timer对象(documentation)可以计算十秒,然后让它设置一个Event标志,指示循环应该退出。

文档显示时间可能不准确 - 您必须测试它是否足够准确适合您的游戏。

答案 4 :(得分:0)

在此示例中,循环每秒运行十秒钟:

import datetime, time
then = datetime.datetime.now() + datetime.timedelta(seconds=10)
while then > datetime.datetime.now():
    print 'sleeping'
    time.sleep(1)

答案 5 :(得分:0)

对于StopWatch助手类,这是我的解决方案,可为您提供精确的输出以及原始的开始时间:

class StopWatch:
    def __init__(self):
        self.start()
    def start(self):
        self._startTime = time.time()
    def getStartTime(self):
        return self._startTime
    def elapsed(self, prec=3):
        prec = 3 if prec is None or not isinstance(prec, (int, long)) else prec
        diff= time.time() - self._startTime
        return round(diff, prec)
def round(n, p=0):
    m = 10 ** p
    return math.floor(n * m + 0.5) / m

答案 6 :(得分:0)

  1. 询问您何时停止[秒]
  2. 在[1-9]开头添加“ 0”
import time
import sys

stop = int(input('> '))
second = 0
print('> Stopwatch Started.')

while stop > second:
    if second < 9:
        second = second + 1
        time.sleep(1)
        sys.stdout.write('\r> ' + '0' + str(second))
    else:
        second += 1
        time.sleep(1)
        sys.stdout.write('\r' + '> ' + str(second))

print('\n> Stopwatch Stopped.')

答案 7 :(得分:-1)

作为我自己的学习练习,我创建了一个类,可以创建一些你可能会觉得有用的秒表计时器实例(我确信在时间模块或类似版本中有更好/更简单的版本)

import time as tm
class Watch:
    count = 0
    description = "Stopwatch class object (default description)"
    author = "Author not yet set"
    name = "not defined"
    instances = []
    def __init__(self,name="not defined"):
        self.name = name
        self.elapsed = 0.
        self.mode = 'init'
        self.starttime = 0.
        self.created = tm.strftime("%Y-%m-%d %H:%M:%S", tm.gmtime())
        Watch.count += 1

    def __call__(self):
        if self.mode == 'running':
            return tm.time() - self.starttime
        elif self.mode == 'stopped':
            return self.elapsed
        else:
            return 0.

    def display(self):
        if self.mode == 'running':
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        print "Name:       ", self.name
        print "Address:    ", self
        print "Created:    ", self.created
        print "Start-time: ", self.starttime
        print "Mode:       ", self.mode
        print "Elapsed:    ", self.elapsed
        print "Description:", self.description
        print "Author:     ", self.author

    def start(self):
        if self.mode == 'running':
            self.starttime = tm.time()
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.starttime = tm.time()
            self.mode = 'running'
            self.elapsed = 0.
        elif self.mode == 'stopped':
            self.mode = 'running'
            #self.elapsed = self.elapsed + tm.time() - self.starttime
            self.starttime = tm.time() - self.elapsed
        else:
            pass
        return

    def stop(self):
        if self.mode == 'running':
            self.mode = 'stopped'
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.mode = 'stopped'
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        return self.elapsed

    def lap(self):
        if self.mode == 'running':
            self.elapsed = tm.time() - self.starttime
        elif self.mode == 'init':
            self.elapsed = 0.
        elif self.mode == 'stopped':
            pass
        else:
            pass
        return self.elapsed

    def reset(self):
        self.starttime=0.
        self.elapsed=0.
        self.mode='init'
        return self.elapsed

def WatchList():
    return [i for i,j in zip(globals().keys(),globals().values()) if '__main__.Watch instance' in str(j)]

答案 8 :(得分:-1)

这是我所知道的最短路:

def stopWatch():
        import time
        a = 0
        hours = 0
        while a < 1:
            for minutes in range(0, 60):
                for seconds in range(0, 60):
                    time.sleep(1)
                    print(hours,":", minutes,":", seconds)
        hours = hours + 1

答案 9 :(得分:-2)

蟒蛇世界的新手!
我需要一个独立于系统时间的秒表,所以我把旧的C ++类翻译成了Python:

from ctypes.wintypes import DWORD
import win32api
import datetime

class Stopwatch:

    def __init__(self):
        self.Restart()

    def Restart(self):
        self.__ulStartTicks = DWORD(win32api.GetTickCount()).value

    def ElapsedMilliSecs(self):
        return DWORD(DWORD(win32api.GetTickCount()).value-DWORD(self.__ulStartTicks).value).value

    def ElapsedTime(self):
        return datetime.timedelta(milliseconds=self.ElapsedMilliSecs())

由于DWORD数学而没有49天的问题,但 NOTICE GetTickCount具有大约15毫秒的粒度,所以如果需要1-100毫秒的时间,请不要使用此类的范围内。

欢迎任何改进或反馈!