Python中的矛盾时间间隔

时间:2014-10-23 18:44:05

标签: python tkinter

我是编程新手(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微秒),这是完整的与我的预期相反。这是代码:

import datetime

a = datetime.datetime.now()
b = datetime.datetime.now()
asec = a.microsecond
bsec = b.microsecond
print bsec-asec   # result is around 300 microseconds

任何人都可以向我解释这个吗?

2 个答案:

答案 0 :(得分:3)

datetime.microseconddatetime对象的微秒组件 - 它以微秒为单位表示的整个日期时间。

为了区分datetime个对象,只需减去它们即可获得timedelta个对象:

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

所以这里的差异是12.4秒,或12秒和431220微秒。

为了衡量两个事件之间的经过时间,time.time()更容易使用,如评论中 @CasualDemon 所述:

>>> import time
>>> start = time.time()
>>> end = time.time()
>>> elapsed = end - start
>>> elapsed
5.727240085601807    # in seconds

答案 1 :(得分:0)

我认为您应该为此使用线程。为按键创建线程,并且您可以在每个线程中计算两次按键之间的时间。有关更多说明,请观看我的视频以获取确切的解决方案。

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