how do I make a Timer in Python - python

How do you create a timer in 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). 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.
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.")

Related

Python - Schedule: Run function every hour + "on the hour"

I'm trying to use the schedule module to do some basic scheduling in a continuously updating script.
Is there a way to set a schedule to run every "x" hours, 'on the hour'?
For example, I'd like to have a function that runs at: [1:02pm, 2:02pm, 3:02pm, 4:02pm] regardless of when I run the script in the first place. In other words, simply doing "schedule.every(1).hours.' doesn't work because I can't guarantee what time the script is run in the first place.
Thanks!
Here you can find examples for case you trying to achieve.
schedule.every().hour.at(":02").do(job)
Here is a simple script:
from datetime import datetime
import time
# scheduled hours in 24-hour format
hours = ["13:2", "14:2", "15:2", "16:2"]
# your function
def foo():
pass
while True:
now = datetime.now() # gets current datetime
hour = str(now.hour) # gets current hour
minute = str(now.minute) # gets current minute
current_time = f"{hour}:{minute}" # combines current hour and minute
# checks if current time is in the hours list
if current_time in hours:
foo()
time.sleep(60) # waits a minute until it repeats
Please note that it will check every minute at the same time when you ran it, and not when the new minute starts. (For instance, if you run it in the middle of the minute, it will check again in the middle of the next minute)

Measure time from one moment to another python

I am coding a simple game in Python 3 and I need to measure the time passed from one moment to another. Ideally I would like a function that starts measuring and another one which returns the time passed. Is this possible?
it's pretty simple, using the stdlib time module:
import time
t1 = time.time()
# other code ...
t_diff = time.time() - t1 # time in seconds

Python: how to extend execution time of code to 1 second

I'm writing a countdown clock in python, but it looks like the time module only goes down to the second. Is there a way for me to accurately determine when exactly 1 second has passed?
Seems like my question was a little confusing, let me clarify. I need to run some code, then, at the end, the program enters a while loop and exits once at least 1000 milliseconds have passed since the time the code started running
If you know the code you want to run will take less than 1 second, then 1 - elapsed time will give you the remaining time to sleep, no while loop required.
now = time.time()
foo()
time.sleep(1 - (time.time() - now))
There will be some overhead with the arithmetic, but it's within 1/100 of a second and will be strictly greater than 1 second, as you request. I ran the following code:
import time
import random
def foo():
time.sleep(random.random())
now = time.time()
foo()
time.sleep(1 - (time.time() - now))
print "Time elapsed: {}".format(time.time() - now)
Output:
Time elapsed: 1.00379300117
You can run this several times to verify it gives the output you want, no matter how long foo takes.
Unless it takes longer than 1 second, then the sleep time will be negative which will result in IOError. You would need to check for that case.
Or, if you need to kill the function if 1 second has passed, check this question
Here is a way which will work, though im not sure which modules you are limited to.
import time
def procedure:
time.sleep(2.5)
# measure wall time
t0 = time.time()
procedure()
print time.time() - t0, "seconds wall time"
2.50023603439 seconds wall time
where procedure is a reference to the function you are timing.
By default the time module gives you the time to the 10^-5 second
import time
time.time()
>>> 1480643510.89443

How can I upload/download a file with python and log the time it takes in each operation?

I am trying to make and ftp client to upload and download a file in python but I need to log the time each operation takes. Hope can I get help in this site. I saw some code here but it shows just how to upload/download but how can I know the time each operation takes?
You can measure the elapsed time by recording the current time before the up- or download, then calculating the number of seconds since the previous time-stamp after the operation:
import time
start = time.time() # seconds since the UNIX epoch
# upload your file
elapsed = time.time() - start
where elapsed will then be a floating point value measuring seconds since the first time.time() call.
Demo:
>>> import time, random
>>> start = time.time()
>>> time.sleep(random.randrange(20)) # random amount of time to wait
>>> print time.time() - start
20.8919820786

execution time in python

Through a python program, sending a command to specific device and that device is responding on the behalf of the command. Now I have to calculate timing between send and receive (means how much time taking to response of the command ).
Ex.
device ip - 10.0.0.10
transmitting 'L004' command through our local system to 10.0.10.
Receving 'L' response from 10.0.0.10.
So now I have to calculate time difference between start time and end time.
Please provide an API through that I can calculate.
import time
t1 = time.time()
# some time-demanding operations
t2 = time.time()
print "operation took around {0} seconds to complete".format(t2 - t1)
time.time() returns the current unix timestamp as a float number. Store this number at given points of your code and calculate the difference. You will get the time difference in seconds (and fractions).
The timeit standard module makes it easy to do this kind of task.
Just Use "timeit" module. It works with both Python 2 And Python 3
import timeit
start = timeit.default_timer()
#ALL THE PROGRAM STATEMETNS
stop = timeit.default_timer()
execution_time = stop - start
print("Program Executed in "+execution_time) #It returns time in sec
It returns in Seconds and you can have your Execution Time. Simple but you should write these in Main Function which starts program execution. If you want to get the Execution time even when you get error then take your parameter "Start" to it and calculate there like
`def sample_function(start,**kwargs):
try:
#your statements
Except:
#Except Statements
stop = timeit.default_timer()
execution_time = stop - start

Categories

Resources