Timing python programs [duplicate] - python

This question already has answers here:
How do I get time of a Python program's execution?
(38 answers)
Closed 4 years ago.
So I am trying to see how long it takes my program to run, and the solution I came up with is:
import datetime
time1 = datetime.datetime.now()
[program code]
time2 = datetime.datetime.now()
print(time2 - time1)
I want to know if this is an efficient/correct solution, because all the guides I could find on the internet would use modules such as timeit, etc.
I would appreciate any feedback.

Yes, that works. However, another solution is:
import time
start = time.time()
# do stuff
print(time.time() - start)
You could also use time.clock() instead of time.time()

Related

How can I run my code at a specific time? [duplicate]

This question already has answers here:
How do I get a Cron like scheduler in Python?
(9 answers)
Closed 1 year ago.
I am developing a software with python. And I want my code to run at certain hours. It will run once every 5 minutes without a break. But I want it to work exactly at certain hours and minutes. For example, such as 20:00, 20:05, 20:10...
I used time.sleep(300) but if for example 5 seconds passes after my program runs, it starts to delay 5 seconds in each run and for example it starts running 1 minute late after 12 runs. For example, it should work at 20:05, but it starts at 20:06.
How can I provide this?
You can use schedule module
import schedule
import time
from datetime import datetime
now = datetime.now()
def omghi():
print("omg hi there xD")
schedule.every(5).minutes.do(omghi)
while True:
schedule.run_pending()
time.sleep(1)
There is a useful model for that case.
It is an external model, you have to download it using pip and it is called
schedule
https://pypi.org/project/schedule/ - here you can see all the details.
I believe that using timed threads works the best with what you want. This excellent answer uses threading.Timer from the library threading as follows:
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
printit()
Thank you very much for the answers. But this is how I handled it and I wanted to share it with you :)
import time
from datetime import datetime
while True:
now = datetime.now()
if (now.minute % 5) == 0 and now.second == 0:
print("Fire!")
time.sleep(1)

Run function at a specific time in python [duplicate]

This question already has answers here:
Start a Function at Given Time
(9 answers)
Closed 3 years ago.
import time
import webbrowser
print(time.ctime())
targetTime = time.ctime()
if(targetTime == "Tue May 01 11:05:17 2018"):
webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
This is what I tried already and it doesn't open the link when the time comes. I read through the time library but I couldn't find anything to help me. My target is for the program to open a link at a time that I want. Any help appreciated.
Python comes built-in with a simple scheduling library called sched that supports this.
import sched, time
def action():
webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
# Set up scheduler
s = sched.scheduler(time.localtime, time.sleep)
# Schedule when you want the action to occur
s.enterabs(time.strptime('Tue May 01 11:05:17 2018'), 0, action)
# Block until the action has been run
s.run()
If you don't mind using third party modules, there's Python pause:
import pause
from datetime import datetime
pause.until(datetime(2018, 5, 1, 11, 5, 17))
webbrowser.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ")

what is the unit of timeit() from python3 timeit module function [duplicate]

This question already has an answer here:
What unit of time does timeit return?
(1 answer)
Closed 4 years ago.
import time
import timeit
start = timeit.timeit()
time.sleep(5)
end = timeit.timeit()
time_elapsed = end - start
print(end)
print(time_elapsed)
print(start)
Outputs:
0.018255482330552297
-0.00033663523232263515
0.018592117562874932
As the documentation clearly says:
This… returns the time it takes to execute the main statement a number of times, measured in seconds as a float.
Meanwhile, notice that this is the elapsed time to run the main statement—that is, nothing at all, in your case. It's not a timestamp or anything like that. So subtracting end - start doesn't give you anything useful—it's the difference in elapsed time for two different runs of a no-op.

Timers in Python [duplicate]

This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
Closed 6 years ago.
I'm working on a problem where I need to print something every 45 seconds. So I have used time.sleep(45) and made up the code as below:
import timer
def print_data():
print "Hello World!"
time.sleep(45)
while True:
print_data()
I have a couple of queries which I'm trying to understand and learn. I have re-searched this but couldn't get a answer I'm looking for. Please find my queries below:
How do I print the above content continuously exactly for 1 hour waiting every 45 sec?
Can we give a random value say, 30-45 seconds waiting time. So it can wait for any value between 30-45 seconds ?
How does RAM or CPU behave when I put on the timer for 4 -5 hours refreshing/waiting every 60 seconds ? Does this effect the CPU or RAM in any way ?
Kindly help me in understanding these questions. Any help would be appreciated. Thanks in advance.
This should do what you are looking for:
import time
from random import randint
def print_data():
print "Hello World!"
time.sleep(randint(30, 45))
def print_data_for(total_time):
start_time = time.time()
while time.time() < start_time + total_time:
print_data()
print_data_for(60*60) # 1 hour
As for the CPU/RAM usage, my experience (I have a script based on sleep that prints regular status messages monitoring another process) is that the process is not very expensive at all while it is idling about, which is confirmed here: Python - is time.sleep(n) cpu intensive?
You could print every random value of seconds, and wait for a keyboard interrupt because time.sleep() does nothing.
import time
from random import randint
def print_data(time, data):
start_time = time.time()
if time.time() < start_time + time:
pass
except KeyBoardInterrupt:
data = raw_input("what's your value?")
print data
else:
print data
data = "Hello World!"
while True:
print_data(data)
if time.time() - start_time > (60*5):
break
print "Done!"
Also to know your CPU and RAM usage, you can use the psutil library https://pypi.python.org/pypi/psutil, psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.
It currently supports Linux, OS X, FreeBSD and Windows with Python versions from 2.4 to 3.1 by using a unique code base.

Python Tkinker events [duplicate]

This question already has answers here:
How can I schedule updates (f/e, to update a clock) in tkinter?
(8 answers)
Closed 8 years ago.
I would want to use time to enable event's callback function in Tkinter.
How do I do something like this using Tkinter
ftime = time()
while 1:
if ftime - time() > 2000:
dosomething
ftime = time()
Note that all I wanted is being able to use time passed to call callback function
Janus
You can use the Tkinter method after to schedule a command to run after a given number of milliseconds. That's considerably better than implementing a tight loop. Remember: the event loop is already an infinite loop, nesting a long running loop inside it causes performance problems.
If you want something to be called more than once after a given period of time you can have a job call itself at regular intervals. There is an example in this answer to the question How to create a timer using tkinter?

Categories