Guest User

Untitled

a guest
Jan 1st, 2018
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Author: ficapy
  4.  
  5. import random
  6. import csv
  7. import time
  8. from functools import wraps
  9. from io import StringIO
  10. from contextlib import closing, contextmanager
  11. from psycopg2.pool import ThreadedConnectionPool
  12. from psycopg2.extras import execute_values
  13.  
  14.  
  15. pool = ThreadedConnectionPool(
  16. 5, ## Min
  17. 20, ## Max
  18. database='dbname',
  19. user='username',
  20. password='pwd')
  21.  
  22.  
  23. @contextmanager
  24. def get_curs():
  25. conn = pool.getconn()
  26. try:
  27. yield conn.cursor()
  28. conn.commit()
  29. except Exception:
  30. conn.rollback()
  31. finally:
  32. pool.putconn(conn)
  33.  
  34.  
  35. def timeit(func):
  36. @wraps(func)
  37. def inner(*args, **kwargs):
  38. with closing(StringIO()) as f, get_curs() as curs:
  39. curs.execute("DROP TABLE IF EXISTS demo;")
  40. curs.execute("""CREATE TABLE IF NOT EXISTS demo (
  41. id INT PRIMARY KEY,
  42. mch_id INT
  43. )""")
  44.  
  45. writer = csv.writer(f)
  46. for i in range(1, 1000000):
  47. writer.writerow(map(str, [i, random.randint(1, 1000)]))
  48. f.seek(0)
  49.  
  50. curs.copy_from(f, 'demo', sep=',')
  51.  
  52. print("start {}".format(func.__name__))
  53. start = time.time()
  54. func(*args, **kwargs)
  55. print("{} elapse times: {}".format(func.__name__, time.time() - start))
  56.  
  57. return inner
  58.  
  59.  
  60. @timeit
  61. def single(data: dict):
  62. for key, value in data.items():
  63. with get_curs() as curs:
  64. curs.execute("UPDATE demo SET mch_id = %s WHERE id = %s", (value,key))
  65.  
  66.  
  67. @timeit
  68. def batch(data: dict):
  69. with get_curs() as curs:
  70. execute_values(curs,
  71. "UPDATE demo SET mch_id=tmp.mch_id FROM (VALUES %s) AS tmp (id,mch_id) WHERE demo.id=tmp.id",
  72. list(data.items()))
  73.  
  74.  
  75. if __name__ == '__main__':
  76. data = {i: random.randint(1, 1000) for i in range(1, 1000000)}
  77. batch(data)
  78. single(data)
  79.  
  80. # Result
  81. # start batch
  82. # batch elapse times: 13.745781898498535
  83. # start single
  84. # single elapse times: 343.0373680591583
Add Comment
Please, Sign In to add comment