简体   繁体   English

如何在 Python 中制作计时器

[英]how do I make a Timer in Python

How do you create a timer in python?如何在 python 中创建计时器? My project is a speed typing test and the timer is there to time the length it takes the user to type.我的项目是一个速度打字测试,计时器用来计时用户打字的长度。 The first task the user types is the alphabet, as fast as they can and then the second task is to type as quickly as possible again for a group of words in set in a random order用户键入的第一个任务是字母表,尽可能快,然后第二个任务是再次以尽可能快的速度再次键入一组以随机顺序排列的单词

The time module时间模块

The time module allows the user to directly get the time, in seconds, since 1970 (See: https://docs.python.org/3/library/time.html ).时间模块允许用户直接获取自 1970 年以来的时间,以秒为单位(参见: https://docs.python.org/3/library/time.ZFC35FDC70D5FC69D269883A822C7A53 )。 This means that we can subtract the time before from time after to see how long it has been, namely how long it took the user to finish the typing test.这意味着我们可以从之后的时间中减去之前的时间看看已经过了多长时间,即用户完成打字测试用了多长时间。 From there, it is as easy as printing the result.从那里开始,就像打印结果一样简单。 You can round the time using int to get a purely seconds result without milliseconds.您可以使用int对时间进行舍入,以获得没有毫秒的纯结果。

The code编码

# Import the time library
import time

# Calculate the start time
start = time.time()

# Code here

# Calculate the end time and time taken
end = time.time()
length = start - end

# Show the results : this can be altered however you like
print("It took", start-end, "seconds!")

You can use the build in time libary:您可以使用及时构建库:

import time
strToType="The cat is catching a mouse."
start_time = time.perf_counter()
print("Type: '"+strToType+"'.")
typedstring=input()
if typedstring==strToType:
    end_time = time.perf_counter()     
    run_time = end_time - start_time
    print("You typed '"+strToType+"' in "+str(run_time)+" seconds.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM