@@ -44,7 +44,6 @@ class Address(Base):
4444# session.commit(). If you're not happy about the changes, you can
4545# revert all of them back to the last commit by calling
4646# session.rollback()
47- session = DBSession ()
4847
4948
5049# add 'npeople' people to the database
@@ -53,29 +52,30 @@ def bench_sqlalchemy(loops, npeople):
5352 total_dt = 0.0
5453
5554 for loops in range (loops ):
56- # drop rows created by the previous benchmark
57- session .query (Person ).delete (synchronize_session = False )
58- session .query (Address ).delete (synchronize_session = False )
59-
60- # Run the benchmark once
61- t0 = pyperf .perf_counter ()
62-
63- for i in range (npeople ):
64- # Insert a Person in the person table
65- new_person = Person (name = "name %i" % i )
66- session .add (new_person )
67- session .commit ()
68-
69- # Insert an Address in the address table
70- new_address = Address (post_code = '%05i' % i , person = new_person )
71- session .add (new_address )
72- session .commit ()
73-
74- # do 100 queries per insert
75- for i in range (npeople ):
76- session .query (Person ).all ()
77-
78- total_dt += (pyperf .perf_counter () - t0 )
55+ with DBSession () as session :
56+ # drop rows created by the previous benchmark
57+ session .query (Person ).delete (synchronize_session = False )
58+ session .query (Address ).delete (synchronize_session = False )
59+
60+ # Run the benchmark once
61+ t0 = pyperf .perf_counter ()
62+
63+ for i in range (npeople ):
64+ # Insert a Person in the person table
65+ new_person = Person (name = "name %i" % i )
66+ session .add (new_person )
67+ session .commit ()
68+
69+ # Insert an Address in the address table
70+ new_address = Address (post_code = '%05i' % i , person = new_person )
71+ session .add (new_address )
72+ session .commit ()
73+
74+ # do 100 queries per insert
75+ for i in range (npeople ):
76+ session .query (Person ).all ()
77+
78+ total_dt += (pyperf .perf_counter () - t0 )
7979
8080 return total_dt
8181
0 commit comments