in mySql I have the following table (named "staff" )of 800 records (might be much higher):
day start_time end_time
-----------------------------------------------------------------
2017-01-05 | 2017-01-05 08:00:00 2017-01-05 17:00:00
2017-01-06 | 2017-01-06 08:00:00 2017-01-06 17:00:00
2017-01-09 | 2017-01-09 08:00:00 2017-01-09 17:00:00
..... | ......
With a given datetime, my python function looks for the closest day in the table (col0) and returns col1 and col2:
from datetime import datetime
import MySQLdb
import MySQLdb.cursors as cursors
import time
conn = MySQLdb.connect("localhost","root","","FOO_DATABASE", cursorclass = cursors.SSCursor )
def foo(x):
c.execute("SELECT start_time, end_time FROM staff WHERE Date >= %s ORDER BY Date LIMIT 1", (x,))
results = c.fetchone()
col1 = results[0]
col2 = results[1]
return col1, col2
#Date_time to look
date_time = datetime.strptime('2017-01-01 12:22:00', "%Y-%m-%d %H:%M:%S")
#The loop
start = time.time()
for i in range(60000):
c = conn.cursor()
foo(date_time)
c.close()
end = time.time()
print round((end - start), 2)
For 60 000 loops (which is not so much regarding my program) it runs in 21 seconds.
I look forward to improve this.
EDIT 1
Well, just created an index on the "day" column and it goes 2 times faster, 9.13 seconds. Hope to improve it because it's not sufficient for my application
EDIT 2
To make in clearer the loop passes 60,000 different values, the use of the fixed value was for illustration purpose.
In my production scheduling algorithm I have to test many combinations of schedules and thus find out the working times for a given datetime. If the date is not in my table (a weekend for example) the function will return the next opening day working time range. Hope it's clear!