I am trying to count how long a very long process is taking:
import datetime
def main(argv):
starttime = datetime.datetime.now()
for f in somearray:
doSomething(f)
endtime = datetime.datetime.now()
deltatime = endtime-starttime
print "Operation took " + str(deltatime.seconds) + " seconds"
def doSomething(f):
# this takes a looong time (~10 minutes)
In the code above I only end up getting the time elapsed for the last time doSomething was run. I used to have doSomething as part of the main function and the timing was fine, but it made sense to move it to its own function.
I saw this question but it seems to serve a different need.
What am I doing wrong?
Thanks
What is the error you are getting? datetime doesn't have a .seconds attribute but it does have a .second attribute. maybe try str(deltatime.second) in your code.
Related
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)
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.")
I am making a Discord bot which allows you to create a poll. The user can put as an argument how long the poll will be. So I want to refresh every 5s or 10s (or maybe more) the message with the poll editing how much time the user has left. I want to implement a countdown from 3600 seconds for example, and every 5s or 10s execute a function which will edit the message until the time goes to 0. Everything on the bot side I have it under control and more or less I know how to implement it.
So, what I thought is making an interval and stop when the current time is equal to time when it started + duration of the poll. So I can use the rx.interval() for creating the observable and use an operator like .take_while().
This is my code:
import time
import rx
print(rx.__version__) # 3.1.1
started_at = time.time() # Time in seconds
end_at = started_at + 3600 # One hour after
source = rx.interval(5).take_while(time.time() < end_at)
But I get AttributeError: 'Observable' object has no attribute 'take_while'.
I think I should put it in a pipe or something like this:
from rx import operators as op
sub = source.pipe(op.take_while(time.time() < end_at))
But I get TypeError: 'bool' object is not callable
How can I use take_while? Thank you!
You should pipe the source and then subscribe. You have to use operators inside of the pipe() method that the Observable has (https://rxpy.readthedocs.io/en/latest/reference_observable.html#rx.Observable.pipe)
The code should look something like this
import time
import rx
from rx import operators as op
print(rx.__version__) # 3.1.1
started_at = time.time() # Time in seconds
end_at = started_at + 3600 # One hour after
ob = rx.interval(5)
sub = ob.pipe(op.take_while(lambda _: time.time() < end_at))
sub.subscribe(lambda i: print(i))
I want to calculate the execution time of code of various languages such as java, python, javascript. How to get the execution time of these codes. Is there any tool available in python packages or any other to calculate the execution time by passing the file(any file java or python) path. Please share your suggestion.
I am aware of getting execution time by using time module in python code. How to execute Javascript and java codes in python and get the execution time in common function.
I tried in below method.
import time
def get_exectime(file_path): # pass path of any file python,java,javascript, html, shell
start_time=time.time()
# execute the file given here. How to execute all file types here?
end_time=time.time()
exec_time=end_time-start_time
print(exec_time)
Is there any other method available to achieve this?
You can do that using the time module:
import time
start_time = time.time()
# your code
end_time = time.time()
print("Total execution time: {} seconds".format(end_time - start_time))
Contrary to other answers, I suggest using timeit, which was designed with the very purpose of measuring execution times in mind, and can also be used as a standalone tool: https://docs.python.org/3/library/timeit.html
It will give you not only the real time of execution, but also CPU time used, which is not necessarily the same thing.
import time
start_time = time.time()
#code here
print("--- %s seconds ---" % (time.time() - start_time))
I think you might need time module. This is the simplest way to measure execution time inn python. Take a look at my example.
import time
start_time = time.time()
a=1
for i in range(10000):
a=a+1
end_time = time.time()
total_time = end_time-start_time
print("Execution time in seconds: %s ",total_time)
Output:
Execution time in seconds: %s 0.0038547515869140625
>>>
First install "humanfriendly" package in python by opening Command Prompt (CMD) as administrator and type -
pip install humanfriendly
Code:
from humanfriendly import format_timespan
import time
begin_time = time.time()
# Put your code here
end_time = time.time() - begin_time
print("Total execution time: ", format_timespan(end_time))
Output:
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