Python中的矛盾时间间隔

2024-06-26 14:30:50 发布

您现在位置:Python中文网/ 问答频道 /正文

作为一个学习练习,我编写了一个Tkinter程序来测量两个“同时”按键之间的时间。我想知道有多少时间是程序的实际处理过程中人为造成的,所以我去掉了实际的输入,让程序模拟一个接一个的按键。得到了预期的短间隔(25-35微秒)。这不是整个程序的重要部分:

def buttonPress1(event):
    a = datetime.datetime.now()
    asec = a.microsecond
    press1.set(asec) 
    onePressed.set(True)
    if onePressed.get() == True and twoPressed.get() == True:
        difference()
    b = datetime.datetime.now()
    bsec = b.microsecond
    press2.set(bsec)
    twoPressed.set(True)
    if onePressed.get() == True and twoPressed.get() == True:
        difference()    



def difference():
    dif = abs(press1.get() - press2.get())  # This is difference in times. Around 30 microseconds
    resultStr = str(dif) + " microseconds"  
    result.set(resultStr)                   # Result is then displayed in a label widget
    onePressed.set(False)
    twoPressed.set(False)

然后我想看看代码的复杂性给时间间隔增加了多少,所以我试了一个真正简单的例子,但是奇怪的是,我得到了更长的间隔(大约300微秒),这与我预期的完全相反。代码如下:

^{pr2}$

有人能给我解释一下吗?在


Tags: 程序truegetdatetime间隔def时间now
2条回答

我想你应该用线。为键创建线程,在每个线程中,您可以计算按键之间的时间间隔。为了得到更多的解释,请看我的视频来了解这个确切的答案。在

https://www.youtube.com/watch?v=sDGYM8LeZh8

参见以下代码:

import keyboard # keyboard library
import string   # string for capturing keyboard key codes
import time     # for capturing time

from threading import * # threads for keypresses

# get the keys
keys = list(string.ascii_lowercase)

# key listener
def listen(key):
    while True:
        global timeda   # global variable for storing time for 1st keypress
        global newda    # global variable for storing time for next keypress

        keyboard.wait(key)  # when key is presses

        # check if variables are defined
        try:
            timeda
            newda

        # this will run for the first keypress only so assign initial time to variable

        except NameError:
            timeda = time.time()
            newda  = time.time()
            print("First key is pressed at "+str(round(newda,2)))
            print('\n==========\n')

        # for all keypresses except for the first will record time here
        else:
            newda = time.time()         # assign time for next keypressed
            newtime = newda - timeda    # get difference between two keys presses

            # just to test time of first keypress
            print("Previous keypress was at "+str(round(timeda,2)))

            # just to test time of next keypress
            print("Current keypress is at "+ str(round(newda,2)))

            # convert time into seconds
            newtime = newtime % 60

            print("Difference between two keypresses is "+str(round(newtime,2)))
            print('\n==========\n')     # need some space for printing difference 
            timeda = time.time()

# creating threads for keys and assigning event and args 
threads = [Thread(target=listen, kwargs={'key':key}) for key in keys]

# calling each thread
for thread in threads:
    thread.start()


# thats it

^{}是一个datetime对象的微秒组件,它不是以微秒表示的整个日期时间。在

为了得到to datetime对象之间的差异,只需减去它们,就可以得到一个^{}对象:

>>> d1 = datetime.now()
>>> d2 = datetime.now()
>>> delta = d2 - d1
>>> delta
datetime.timedelta(0, 12, 431220)
>>> delta.seconds
12
>>> delta.microseconds
431220

所以这里的区别是12.4秒,或者12秒和{}微秒。在

然而,对于测量两个事件之间的运行时间,^{}更容易使用,正如@CasualDemon在评论中所述:

^{pr2}$

相关问题 更多 >