考虑以下两个Python代码示例,它们实现相同但具有显着和令人惊讶的性能差异。Postgres:使用光标更新时的令人惊讶的性能
import psycopg2, time
conn = psycopg2.connect("dbname=mydatabase user=postgres")
cur = conn.cursor('cursor_unique_name')
cur2 = conn.cursor()
startTime = time.clock()
cur.execute("SELECT * FROM test for update;")
print ("Finished: SELECT * FROM test for update;: " + str(time.clock() - startTime));
for i in range (100000):
cur.fetchone()
cur2.execute("update test set num = num + 1 where current of cursor_unique_name;")
print ("Finished: update starting commit: " + str(time.clock() - startTime));
conn.commit()
print ("Finished: update : " + str(time.clock() - startTime));
cur2.close()
conn.close()
和:
import psycopg2, time
conn = psycopg2.connect("dbname=mydatabase user=postgres")
cur = conn.cursor('cursor_unique_name')
cur2 = conn.cursor()
startTime = time.clock()
for i in range (100000):
cur2.execute("update test set num = num + 1 where id = " + str(i) + ";")
print ("Finished: update starting commit: " + str(time.clock() - startTime));
conn.commit()
print ("Finished: update : " + str(time.clock() - startTime));
cur2.close()
conn.close()
为表测试CREATE语句是:
CREATE TABLE test (id serial PRIMARY KEY, num integer, data varchar);
这表包含10万行和真空分析测试;已经运行。
我在几次尝试中得到了以下结果。
第一个代码示例:
Finished: SELECT * FROM test for update;: 0.00609304950429
Finished: update starting commit: 37.3272754429
Finished: update : 37.4449708474
第二个代码示例:
Finished: update starting commit: 24.574401185
Finished committing: 24.7331461431
这是非常令人惊讶的我,我会觉得是应该是完全相反的,这意味着使用光标的更新应该是根据this回答显着更快。