Advertisement
aibaq

Untitled

Feb 25th, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. import random
  2. import string
  3.  
  4. from django.db import connection,transaction
  5. cursor = connection.cursor()
  6. s = """insert into main_contact(name, number, uuid, country_code, timestamp, like_count, visible)
  7. (
  8. select a.name, a.number, a.uuid, a.country_code, now() as timestamp, 0 as like_count, true as visible
  9. from (
  10. select *
  11. from unnest(
  12. string_to_array('{}', ','),
  13. string_to_array('{}', ','),
  14. string_to_array('{}', ','),
  15. string_to_array('{}', ',')
  16. ) WITH ORDINALITY
  17. AS t(name, number, uuid, country_code)
  18.  
  19. ) a
  20. left join main_contact b on a.number = b.number and a.name = b.name
  21. where b.number IS NULL
  22. );
  23. """
  24.  
  25. N = 1000
  26.  
  27. names = ','.join(''.join([random.choice(string.ascii_letters) for _ in range(10)]) for _ in range(N))
  28. numbers = ','.join(''.join([random.choice(string.digits) for _ in range(10)]) for _ in range(N))
  29. uuids = ','.join(''.join([random.choice(string.ascii_letters) for _ in range(10)]) for _ in range(N))
  30. countries = ','.join(random.choice(['KZ', 'RU']) for _ in range(N))
  31.  
  32.  
  33. def a(names, numbers, uuids, countries):
  34. t1 = time.time()
  35. s2 = s.format(names, numbers, uuids, countries)
  36. cursor.execute(s2)
  37. transaction.commit()
  38. return time.time() - t1
  39.  
  40. a(names, numbers, uuids, countries)
  41.  
  42. def add_contacts_async(contacts, uuid, country_code):
  43. from main.models import Contact
  44. numbers = [x['number'] for x in contacts]
  45. data = list(Contact.objects.filter(number__in=numbers).values('name', 'number'))
  46. new_contacts = list()
  47. for c in contacts:
  48. if {'name': c['name'], 'number': c['number']} not in data:
  49. new_contacts.append(Contact(name=c['name'], number=c['number'],
  50. uuid=uuid,
  51. country_code=country_code))
  52. Contact.objects.bulk_create(new_contacts)
  53.  
  54.  
  55. cc = [{'name': ''.join([random.choice(string.ascii_letters) for _ in range(10)]), 'number': ''.join([random.choice(string.digits) for _ in range(10)])} for _ in range(N)]
  56. def b():
  57. t1 = time.time()
  58. add_contacts_async(cc, 'asd', 'KZ')
  59. return time.time() - t1
  60. b()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement