Commit 152f7d86 by John Eskew

Add saving times to SQLite

parent 9b08e26b
from timeit import default_timer from timeit import default_timer
from .storage import TimingDataStorage
nest_level = 0
class CodeBlockTimer(object): class CodeBlockTimer(object):
def __init__(self, block_desc, verbose=False): def __init__(self, block_desc, verbose=False):
self.block_desc = block_desc self.block_desc = block_desc
self.verbose = verbose self.verbose = verbose
self.timer = default_timer self.timer = default_timer
self.data_store = TimingDataStorage()
self.run_id = None
def __enter__(self): def __enter__(self):
if nest_level == 0:
self.run_id = self.data_store.run_id()
nest_level += 1
self.start = self.timer() self.start = self.timer()
return self return self
...@@ -15,6 +24,10 @@ class CodeBlockTimer(object): ...@@ -15,6 +24,10 @@ class CodeBlockTimer(object):
end = self.timer() end = self.timer()
self.elapsed_secs = end - self.start self.elapsed_secs = end - self.start
self.elapsed = self.elapsed_secs * 1000 # millisecs self.elapsed = self.elapsed_secs * 1000 # millisecs
self.data_store.store(self.run_id, self.block_desc, self.elapsed)
nest_level -= 1
if nest_level == 0:
self.run_id = None
if self.verbose: if self.verbose:
print '{}: elapsed time: {} ms'.format(self.block_desc, self.elapsed) print '{}: elapsed time: {} ms'.format(self.block_desc, self.elapsed)
CREATE TABLE test_run (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
run_desc TEXT
);
CREATE TABLE block_times (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
run_id INTEGER,
block_desc TEXT,
elapsed REAL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
import sqlite3
# Assumes that the DB exists and the schema in schema.sql exists in it.
class TimingDataStorage(object):
DB_NAME = 'block_times.db'
def __init__(self):
# Verify that the sqlite DB and schema exists.
self.conn = sqlite3.connect(self.DB_NAME)
def run_id(self, desc):
"""
Creates a new run ID and returns it.
A single run ID can be used for multiple store()s for times in the same test.
"""
cur = self.conn.cursor()
cur.execute('insert into test_run (run_desc) values (?)', (desc,))
self.conn.commit()
cur.execute('select max(id) from test_run')
return cur.fetchone()[0]
def store(self, run_id, desc, elapsed):
"""
Store the description and elapsed time in the DB, under the passed-in run_id.
"""
cur = self.conn.cursor()
cur.execute('insert into block_times (run_id, block_desc, elapsed) values (?, ?, ?)', (run_id, desc, elapsed))
self.conn.commit()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment