Mysql保持連線和每次重連--以及--迴圈提交和事務形式提交在插入時的耗時對比分析
阿新 • • 發佈:2018-12-20
前言:
在程式碼中考慮到不同的情況:
- 有時候希望資料庫保持連線,有時候希望在每次使用後斷開;
- 有時候希望以單條形式提交,有時候希望以事務提交;
- 有時候兩者皆可,糾結於此。
這裡給大家提供個人測試資料,以供參考:
測試條件:
- python pymsql
- 阿里雲資料庫,公網連線
- 本地直接迴圈產生簡單資料10條、50條、100條
測試資料:
插入10條 :
1. 保持連線,分條提交: 1.9407286643981934
2. 按次連線,分條提交: 5.170012950897217
3. 保持連線,統一提交: 1.2323071956634521
插入50條:
1. 保持連線,分條提交: 7.82186484336853 2. 按次連線,分條提交: 26.237579107284546 3. 保持連線,統一提交: 4.316909313201904
插入100條:
1. 保持連線,分條提交: 15.691459894180298
2. 按次連線,分條提交: 52.294713258743286
3. 保持連線,統一提交: 7.723136901855469
執行截圖:
圖
分析和結論:
分析:
- 以[1.]為參照,[2.]做對照: 對照[2.]耗時遠大於[1.]
- 以[1.]為參照,[3.]做對照: 對照[3.]耗時小於[1.]
結論:
在本條件中:
- 保持連線速度優於按次連線
- 以事務形式提交速度優於按次提交
測試程式碼:
注:資料庫資訊已隱去
import pymysql
import time
range_nums = 100
host = None # str
user = None
passwd = None
database = None
table = pymysql.escape_string(None) # str
upload_key = pymysql.escape_string(None) # str
def together_init():
"""保持連線,分條提交"""
db = pymysql.connect(host=host, user=user, passwd=passwd, database=database) # 公網,mysql
cursor = db.cursor()
for i in range(range_nums):
sql = "insert into `{0}` (`{1}`) value ('{2}')".format(table, upload_key, str(i))
cursor.execute(sql)
db.commit()
db.close()
def cycle_init():
"""按次連線,分條提交"""
for i in range(range_nums):
db = pymysql.connect(host=host, user=user, passwd=passwd, database=database) # 公網,mysql
cursor = db.cursor()
sql = "insert into `{0}` (`{1}`) value ('{2}')".format(table, upload_key, str(i))
cursor.execute(sql)
db.commit()
db.close()
def together_commit_and_init():
"""保持連線,統一提交"""
db = pymysql.connect(host=host, user=user, passwd=passwd, database=database) # 公網,mysql
cursor = db.cursor()
for i in range(range_nums):
sql = "insert into `{0}` (`{1}`) value ('{2}')".format(table, upload_key, str(i))
cursor.execute(sql)
db.commit()
db.close()
t1 = time.time()
together_init()
t2 = time.time()
t = t2-t1
print("together init:", t) # 100次,保持連線,分條提交:together init: 15.691459894180298 s
t1 = time.time()
cycle_init()
t2 = time.time()
t = t2-t1
print("cycle init:", t) # 100次,按次連線,分條提交:cycle init: 52.294713258743286 s
t1 = time.time()
together_commit_and_init()
t2 = time.time()
t = t2-t1
print("together init and commit:", t) # 100次,保持連線,統一提交:together init and commit: 7.723136901855469 s