How to count elapsed time on Python - python

I have the following code:
def base(nomor)
day = localtime.tm_wday
time = localtime.tm_hour
no = str(nomor)
dosen = cek_dosen(no)
if dosen == 'null':
no_dosen()
elif dosen != 'null':
ada_dosen()
matkul = cek_jadwal(day,time,dosen)
if matkul == 'null':
no_jadwal()
elif matkul != 'null':
ada_jadwal()
pertemuan = cek_pertemuan(matkul)
print pertemuan
if pertemuan > 1:
cek_before(pertemuan)
filename = ''.join([dosen, matkul, str(pertemuan), ".pptx"])
else:
filename = ''.join([dosen, matkul, str(pertemuan), ".pptx"])
grabfile(filename)
os.system(''.join(["loimpress ",filename]))
pertemuan = pertemuan + 1
update_pertemuan(pertemuan,matkul)
mulai()
if __name__ == '__main__':
mulai()
while True:
data = port.read()
count += 1
if count == 1:
if str(data) != start:
nomor = ''
count = 0
elif 2 <= count <= 13:
nomor = nomor + str(data)
elif count == 16 and str(data) == stop:
base(nomor)
nomor = ''
count = 0
I want to count time elapse from after data = port.read() until after grabfile(filename). I've used start = time.time() after data = port.read and end = time.time() after grabfile, time = end - start, but it stuck after data = port.read() so I use Ctrl + C to stop that. If I put start = time.time() after no = str(nomor), I get Attribute Error : 'int' object has no attribute 'time'.
How do I count the elapsed time?

from time import clock
start = clock()
...
print "Time taken = %.5f" % (clock() - start)

Summarized:
import datetime
if __name__ == "__main__":
d1 = datetime.datetime.now()
data = port.read()
# Do more things ...
tdelta = datetime.datetime.now() - d1
print(tdelta.total_seconds()) # This is your answer

Take a look at the python timeit module.
Basic example:
>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)

Related

Python says "UnboundLocalError: local variable 'key' referenced before assignment"

i understand that this error happens when a variable gets mentioned before its defined but "key" is assigned to its value. I started learning python a week ago so i am sorry if my question has a really simple answer.
the code:
from stat import SF_APPEND
import time
import random
keyType = 0
key = 0
deCypherKey = 0
operationType = 0
needToLoop = True
alphabet = "abcdefghijklmnopqrstuvwxyz "
print("ogulSifreleyici v1.0")
time.sleep(0.3)
print("Ipucu: Hem Sifrelemek Hem de Desifrelemek Icin Programi 2 Kere Calistirabilirsiniz")
def cypher():
message = input("Mesajini Gir:\n")
message = message.lower()
unCypheredMessageLength = len(message)
letterOfMessageInQueue = 0
keyStr = str(key)
keyStrInt = 0
whichOrderOfAlphabet = 0
whichLetterOfAlphabet = " "
whichDigitOfKey = 0
orderOfCypheredLetter = 0
cypheredLetter = "a"
cypheredMessageList = []
cypheredStr = ""
while unCypheredMessageLength > 0:
whichLetterOfAlphabet = alphabet[whichOrderOfAlphabet]
if message[letterOfMessageInQueue] == whichLetterOfAlphabet:
print("match")
print(whichOrderOfAlphabet, message[letterOfMessageInQueue], whichLetterOfAlphabet)
keyStrInt = int(keyStr[whichDigitOfKey])
orderOfCypheredLetter = whichOrderOfAlphabet + keyStrInt
if orderOfCypheredLetter > 26:
orderOfCypheredLetter = orderOfCypheredLetter - 26
cypheredLetter = alphabet[orderOfCypheredLetter]
cypheredMessageList.append(cypheredLetter)
unCypheredMessageLength = unCypheredMessageLength - 1
letterOfMessageInQueue = letterOfMessageInQueue + 1
whichOrderOfAlphabet = 0
whichDigitOfKey = whichDigitOfKey + 1
if whichDigitOfKey > 4:
whichDigitOfKey = whichDigitOfKey - 5
if len(cypheredMessageList) == len(message):
cypheredStr = "".join(cypheredMessageList)
print("Sifrelenmis Mesajiniz:\n" + cypheredStr)
time.sleep(1)
lastUserAnswer = input("1-Sifrele(Ayni Anahtar) 2-Sifrele(Farkli Anahtar)\n")
if lastUserAnswer == "1":
cypher()
if lastUserAnswer == "2":
key = input("Anahtar Giriniz(5 Haneli Sayi):\n")
while len(str(key)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
cypher()
cypher()
else:
whichOrderOfAlphabet = whichOrderOfAlphabet + 1
def deCypher():
deCypherMessage = input("Sifreli Mesajinizi Giriniz:\n")
operationType = input("1-Sifrele 2-DeSifrele\n")
while needToLoop == True:
if operationType == "1":
keyType = input("1-Anahtar gir(5 haneli sayi) 2-Rastgele Anahtar\n")
if keyType == "1":
key = input("Anahtar Giriniz:\n")
while len(str(key)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
needToLoop = False
cypher()
needToLoop = False
cypher()
if keyType == "2":
key = int(random.uniform(10000, 100000))
print("Anahtariniz: " + str(key))
cypher()
needToLoop = False
else:
print("Lutfen Seceneklerden Birini Seciniz")
needToLoop = True
if operationType == "2":
deCypherKey = input("Anahtarinizi Giriniz:\n")
while len(str(deCypherKey)) != 5:
key = input("Lutfen Bes Haneli Bir Sayi Giriniz\n")
if len(str(key)) == 5:
needToLoop = False
deCypher()
needToLoop = False
deCypher()
else:
print("Lutfen Seceneklerden Birini Seciniz")
needToLoop = True
this is not exactly the reason you wrote, the fact is that the function cannot see variables that are outside the function. In order for the function to see them, you need to pass the variable as an argument to the function. That is, you need to change line 86 like this: cypher(key). But as you can see, this will give an error, because your function initially does not accept any arguments, in order to fix this we need to add the key argument in line 16 like this: def cypher(key):. There is the site where you can read more about it https://levelup.gitconnected.com/5-types-of-arguments-in-python-function-definition-e0e2a2cafd29

Don't understand this timed while loop attribute error

So I have been trying to make a while loop that will run for 10 minutes. But is keeps erroring out on the line with the while loop. It says 'str' object has no attribute 'time'.
I have discovered that if i remove the lines with now.strftime() in them that the code runs but I don't know why it runs without those lines or how to fix it.
I did also try to do something using the datetime module instead of importing the time module but this also fails.
import math
from datetime import datetime
import time
test_num = 1
largest_loop = 0
delay = 60 * 10
end_time = time.time() + delay
def even_number(value):
if value == 2:
return True
def divide_five(value):
if value == 5:
return True
def is_square(value):
if math.sqrt(value).is_integer():
return False
def multiple_of(value):
if value == 2:
return True
def is_happy():
global check
if check == 1:
return True
while time.time() <= end_time:
test_num += 1
check = test_num
now = datetime.now()
loop_counter = 0
record_loop = 6
date = now.strftime("%m/%d/%Y")
time = now.strftime("%H:%M:%S")
if even_number(test_num) == True:
if divide_five(test_num) == True:
if is_square(test_num) == True:
for _ in range(record_loop + 4):
loop_counter += 1
if is_happy() == True:
if multiple_of(test_num) == True:
#print(test_num)
record_loop = loop_counter
break
else:
pass
else:
pass
else:
pass
else:
pass
else:
pass
As #CoryKramer pointed out, you named a variable time, which is also the name of the module you are importing. All I really did was change the time variable to something like currTime. Try the code below (runs for me):
import math
from datetime import datetime
import time
test_num = 1
largest_loop = 0
delay = 60 * 10
end_time = time.time() + delay
def even_number(value):
if value == 2:
return True
def divide_five(value):
if value == 5:
return True
def is_square(value):
if math.sqrt(value).is_integer():
return False
def multiple_of(value):
if value == 2:
return True
def is_happy():
global check
if check == 1:
return True
while time.time() <= end_time:
test_num += 1
check = test_num
now = datetime.now()
loop_counter = 0
record_loop = 6
date = now.strftime("%m/%d/%Y")
currTime = now.strftime("%H:%M:%S")
if even_number(test_num) == True:
if divide_five(test_num) == True:
if is_square(test_num) == True:
for _ in range(record_loop + 4):
loop_counter += 1
if is_happy() == True:
if multiple_of(test_num) == True:
#print(test_num)
record_loop = loop_counter
break
else:
pass
else:
pass
else:
pass
else:
pass
else:
pass
Additionally, consider reading up on:
How to name a module without conflict with variable name?
https://en.wikipedia.org/wiki/Variable_shadowing
dont name your variable in your while loop time when you import the time library:
time = now.strftime("%H:%M:%S")
in your while loop you want to use the time function of the time library but as soon as you run the while loop once it will try to use time() on the string time you defined in the while loop.
I think the problem is here:
time = now.strftime("%H:%M:%S")
Thus, you converted time into a string variable. Name this variable in a different way!
Apart from this, running for 10 minutes at "full throttle" is a lot! Consider to introduce a "sleep" time at the end of the while loop (just suggesting)

datetime format over 24 hours

I'm trying to add time and have the output as hh:mm:ss, but when datetime gets over 24 hours it becomes x Days, hh:mm:ss. Is there anyway to only have hh:mm:ss greater than 24 hours?
import datetime
from datetime import timedelta
# intro
print("Welcome to TimeCalc")
print("Calculating Durations")
clear = True
while clear == True:
# first input
firstNumber = True
while firstNumber == True:
time_1 = input("Please enter a time [hh:mm:ss] including 0s: ")
if len(time_1) > 0 and len(time_1) >= 8 and time_1[-6] == ":" and time_1[-3] == ":" and int(time_1[-5:-3]) < 60 and int(time_1[-2:]) < 60:
hours_1 = time_1[:-6]
minutes_1 = time_1[-5:-3]
seconds_1 = time_1[-2:]
hours_1 = int(hours_1)
minutes_1 = int(minutes_1)
seconds_1 = int(seconds_1)
firstNumber = False
else:
print("Invalid Syntax")
time_1 = datetime.timedelta(hours=hours_1, minutes=minutes_1, seconds=seconds_1)
cont = True
while cont == True:
# second input
secondNumber = True
while secondNumber == True:
time_2 = input("Please enter a time to add [hh:mm:ss] including 0s: ")
if len(time_2) > 0 and len(time_2) >= 8 and time_2[-6] == ":" and time_2[-3] == ":" and int(time_2[-5:-3]) < 60 and int(time_2[-2:]) < 60:
hours_2 = time_2[:-6]
minutes_2 = time_2[-5:-3]
seconds_2 = time_2[-2:]
hours_2 = int(hours_2)
minutes_2 = int(minutes_2)
seconds_2 = int(seconds_2)
secondNumber = False
else:
print("Invalid Syntax")
time_2 = datetime.timedelta(hours = hours_2, minutes = minutes_2, seconds = seconds_2)
total = time_1 + time_2
print("The total duration is: " + str(total))
# continue, clear, or exit
choice = input("Continue: Y | Clear: N | Exit: X: ")
if choice == "Y" or choice == "y":
time_1 = total
elif choice == "N" or choice == "n":
cont = False
elif choice == "X" or choice == "x":
quit()
after total variable, can you try to put this code, maybe this is not a super solution but it works
seconds = int(total.total_seconds())
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
print("The total duration is: {h:02d}:{m:02d}:{s:02d}".format(h=hours,
m=minutes, s=seconds))
Use the .strftime() method to format your datetime string.
For example,
>>> import datetime
>>> d = datetime.delta(hours=1)
>>> dt = datetime.datetime(2017,10,30,23,10,10) + d
>>> dt.strftime("%H:%M:%S")
'00:10:10'
Hope it help.

Python dictionary lookup performance, get vs in

This isn't premature optimization. My use case has the double-checking of dict's right in the inner-most of inner loops, running all the time. Also, it's intellectually irksome (see results).
Which of these approaches is faster?
mydict = { 'hello': 'yes', 'goodbye': 'no' }
key = 'hello'
# (A)
if key in mydict:
a = mydict[key]
do_things(a)
else:
handle_an_error()
# vs (B)
a = mydict.get(key,None)
if a is not None:
do_things(a)
else:
handle_an_error()
Edit: these are the same speed. Common sense tells me that (B) should be noticeably faster since it's only one dict lookup vs. 2, but the results are different. I'm scratching my head.
Results of a benchmark averaged over 12 runs, 1/2 of which are hits, the other half are misses:
doing in
switching to get
total time for IN: 0.532250006994
total time for GET: 0.480916659037
times found: 12000000
times not found: 12000000
And when a similar one is run (*10 more loops) without ever finding the key,
doing in
switching to get
total time for IN: 2.35899998744
total time for GET: 4.13858334223
Why!?
(correct) code
import time
smalldict = {}
for i in range(10):
smalldict[str(i*4)] = str(i*18)
smalldict["8"] = "hello"
bigdict = {}
for i in range(10000):
bigdict[str(i*100)] = str(i*4123)
bigdict["hello"] = "yes!"
timetotal = 0
totalin = 0
totalget = 0
key = "hello"
found= 0
notfound = 0
ddo = bigdict # change to smalldict for small dict gets
print 'doing in'
for r in range(12):
start = time.time()
a = r % 2
for i in range(1000000):
if a == 0:
if str(key) in ddo:
found = found + 1
foo = ddo[str(key)]
else:
notfound = notfound + 1
foo = "nooo"
else:
if 'yo' in ddo:
found = found + 1
foo = ddo['yo']
else:
notfound = notfound + 1
foo = "nooo"
timetotal = timetotal + (time.time() - start)
totalin = timetotal / 12.0
print 'switching to get'
timetotal = 0
for r in range(12):
start = time.time()
a = r % 2
for i in range(1000000):
if a == 0:
foo = ddo.get(key,None)
if foo is not None:
found = found + 1
else:
notfound = notfound + 1
foo = "nooo"
else:
foo = ddo.get('yo',None)
if foo is not None:
found = found + 1
notfound = notfound + 1
else:
notfound = notfound + 1
foo = "oooo"
timetotal = timetotal + (time.time() - start)
totalget = timetotal / 12
print "total time for IN: ", totalin
print 'total time for GET: ', totalget
print 'times found:', found
print 'times not found:', notfound
(original) code
import time
smalldict = {}
for i in range(10):
smalldict[str(i*4)] = str(i*18)
smalldict["8"] = "hello"
bigdict = {}
for i in range(10000):
bigdict[str(i*100)] = str(i*4123)
bigdict["8000"] = "hello"
timetotal = 0
totalin = 0
totalget = 0
key = "hello"
found= 0
notfound = 0
ddo = bigdict # change to smalldict for small dict gets
print 'doing in'
for r in range(12):
start = time.time()
a = r % 2
for i in range(10000000):
if a == 0:
if key in ddo:
foo = ddo[key]
else:
foo = "nooo"
else:
if 'yo' in ddo:
foo = ddo['yo']
else:
foo = "nooo"
timetotal = timetotal + (time.time() - start)
totalin = timetotal / 12.0
print 'switching to get'
timetotal = 0
for r in range(12):
start = time.time()
a = r % 2
for i in range(10000000):
if a == 0:
foo = ddo.get(key,None)
if foo is not None:
# yaaay
pass
else:
foo = "nooo"
else:
foo = ddo.get('yo',None)
if foo is not None:
#yaaay
pass
else:
foo = "oooo"
timetotal = timetotal + (time.time() - start)
totalget = timetotal / 12
print "total time for IN: ", totalin
print 'total time for GET: ', totalget
We can do some better timings:
import timeit
d = dict.fromkeys(range(10000))
def d_get_has(d):
return d.get(1)
def d_get_not_has(d):
return d.get(-1)
def d_in_has(d):
if 1 in d:
return d[1]
def d_in_not_has(d):
if -1 in d:
return d[-1]
print timeit.timeit('d_get_has(d)', 'from __main__ import d, d_get_has')
print timeit.timeit('d_get_not_has(d)', 'from __main__ import d, d_get_not_has')
print timeit.timeit('d_in_has(d)', 'from __main__ import d, d_in_has')
print timeit.timeit('d_in_not_has(d)', 'from __main__ import d, d_in_not_has')
On my computer, the "in" variants are faster than the .get variants. This is probably because .get is an attribute lookup on the dict and an attribute lookup is likely to be as expensive as a membership test on the dict. Note that in and item lookup using dict[x] can be done directly in bytecode so the normal method lookups can be bypassed...
It also might be worth pointing out that I get a HUGE optimization if I just use pypy :-):
$ python ~/sandbox/test.py
0.169840812683
0.1732609272
0.122044086456
0.0991759300232
$ pypy ~/sandbox/test.py
0.00974893569946
0.00752687454224
0.00812077522278
0.00686597824097

Any idea what's wrong with my code on python?

ihave this code
import serial
import time
import datetime
import MySQLdb as mdb
localtime = time.localtime(time.time())
port = serial.Serial("/dev/ttyUSB0", baudrate=9600)
count = 0
nomor =''
start = '\x02'
stop = '\x03'
def mulai():
print "Silahkan tempel kartu anda"
def no_dosen()
print "Dosen tidak terdaftar"
mulai()
def no_jadwal()
print "Tidak ada jadwal kuliah"
mulai()
def ada_dosen(dosen)
print dosen
return
def ada_matkul(matkul)
print matkul
return
def cek_dosen(no)
db = mdb.connect("localhost", "azis48", "azis48", "skripsi")
cur = db.cursor()
cond1 = "SELECT * FROM dosen WHERE kode_dosen = %s" %(no)
try:
cur.execute(cond1)
hitung = cur.rowcount
res1 = cur.fetchall()
for row in res1:
nama_dosen = row[1]
if hitung == 1:
return nama_dosen
elif hitung != 1:
return 'null'
except:
db.close()
def cek_jadwal(day,time)
db = mdb.connect("localhost", "azis48", "azis48", "skripsi")
cur = db.cursor()
cond2 = "SELECT nama_mk FROM jadwal WHERE hari = '%s' AND waktu = '%s'" %(day,time)
try:
cur.execute(cond2)
hitung = cur.rowcount
res2 = cur.fetchall()
for row in res2:
nama_mk = row[1]
if hitung == 1:
return nama_mk
elif hitung != 1:
return 'null'
except:
db.close()
def cek_pertemuan(matkul)
db = mdb.connect("localhost", "azis48", "azis48", "skripsi")
cur = db.cursor()
cond3 = "SELECT pertemuan_ke FROM acara WHERE nama_mk = '%s'" %(matkul)
try:
cur.execute(cond3)
res3 = cur.fetchall()
for row in res3:
pertemuan_ke = row[0]
return pertemuan_ke
except:
db.close()
def base()
day = localtime.tm_wday
time = localtime.tm_hour
no = str(nomor)
dosen = cek_dosen(no)
if dosen == 'null':
no_dosen()
elif dosen != 'null':
ada_dosen()
matkul = cek_jadwal(day,time)
if matkul == 'null':
no_jadwal()
elif matkul != 'null':
ada_matkul()
pertemuan = cek_pertemuan(matkul)
print pertemuan
mulai()
if __name__ == '__main__':
mulai()
while True:
data = port.read()
count += 1
if count == 1:
if str(data) != start:
nomor = ''
count = 0
elif 2 <= count <= 13:
nomor = nomor + str(data)
elif count == 16 and str(data) == stop:
base(nomor)
nomor = ''
count = 0
everytime i run this code, its only print the ada_dosen function from all in def base(), if i stop it with ctrl+c here is the traceback
DOSEN3
Traceback(most recent call last):
file "skripsi.py", line 111, in<module>
base(nomor)
any ide what wrong so all function on my def base() running?
There are some issues in your code, to highlight a few -
All your functions are defined as def <function name>() , you do not have an ending : , without that you should most probably be getting syntax errors.
You have defined your base function as def base() , but in your main part of the program, you are trying to call it by passing an argument nomor as base(nomor) , I think you need to change the function defnition to accept the argument as - def base(nomor):

Categories

Resources