Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.23 KB | None | 0 0
  1. """
  2. Copyright (c) 2019 Textkernel BV
  3.  
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10.  
  11. The above copyright notice and this permission notice shall be included in all
  12. copies or substantial portions of the Software.
  13.  
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. SOFTWARE.
  21. """
  22.  
  23. import functools
  24. from collections import namedtuple
  25. from timeit import default_timer as timer
  26.  
  27. import py2neo
  28. from neo4j.v1 import GraphDatabase
  29.  
  30. Test = namedtuple('Test', ['name', 'kwargs'])
  31.  
  32.  
  33. class TestRunner:
  34.     def __init__(self):
  35.         username = ''
  36.         password = ''
  37.         self.connectors = [
  38.             py2neoConnector(username, password),
  39.             py2neoConnector(username, password, scheme='http'),
  40.             Neo4jDriverConnector(username, password)
  41.         ]
  42.         self.max_name_len = max(len(connector.name) for connector in self.connectors)
  43.  
  44.         self.lexical_term_names = [line.strip() for line in open('lexical_term_names.txt')]
  45.         self.tests = [
  46.             Test('count_all', {}),
  47.             Test('retrieve_nodes_by_limit', {'limit': 10}),
  48.             Test('retrieve_nodes_by_limit', {'limit': 100}),
  49.             Test('retrieve_nodes_by_limit', {'limit': 1000}),
  50.             # Test('retrieve_nodes_by_limit', {'limit': 10000}),
  51.             # Test('retrieve_nodes_by_limit', {'limit': 100000}),
  52.             # Test('retrieve_nodes_by_limit', {'limit': 1000000}),
  53.             Test('retrieve_nodes_by_name', {'names': self.lexical_term_names[:10]}),
  54.             Test('retrieve_nodes_by_name', {'names': self.lexical_term_names[:100]}),
  55.             Test('retrieve_nodes_by_name', {'names': self.lexical_term_names[:1000]}),
  56.             Test('retrieve_nodes_by_name', {'names': self.lexical_term_names[:10000]}),
  57.             # Test('retrieve_nodes_by_name', {'names': self.lexical_term_names[:50000]}),
  58.         ]
  59.  
  60.     def run_tests(self, repetitions=10):
  61.         print(f"Testing with {repetitions} repetitions", end='\n\n')
  62.         for test in self.tests:
  63.             print(str(test)[:250])
  64.             for connector in self.connectors:
  65.                 raw_method = getattr(connector, test.name)
  66.                 if self.is_method_of_super_class(raw_method, connector):
  67.                     continue
  68.  
  69.                 prepared_method = functools.partial(raw_method, **test.kwargs)
  70.                 times = [self.timeit_ms(prepared_method) for _ in range(repetitions)]
  71.                 display_times = ', '.join([f'{time:.2f}' for time in times])
  72.                 print(
  73.                     f"\t{connector.name:<{self.max_name_len}} took {self.average(times):.1f}ms ({display_times})")
  74.  
  75.     @staticmethod
  76.     def timeit_ms(method):
  77.         start = timer()
  78.         method()
  79.         end = timer()
  80.         return (end - start) * 1000
  81.  
  82.     @staticmethod
  83.     def average(values):
  84.         return sum(values) / len(values)
  85.  
  86.     @staticmethod
  87.     def is_method_of_super_class(method, connector):
  88.         # connector
  89.         class_name_string = str(type(connector))
  90.         cleaned_class_name_string = class_name_string[class_name_string.find('.') + 1:-2]
  91.  
  92.         # method
  93.         method_string = str(method)
  94.         method_parent_string = method_string[14:method_string.find('.')]
  95.  
  96.         return cleaned_class_name_string != method_parent_string
  97.  
  98.  
  99. class AbstractConnector:
  100.     def count_all(self):
  101.         raise NotImplementedError()
  102.  
  103.     def retrieve_nodes_by_limit(self, limit):
  104.         raise NotImplementedError
  105.  
  106.     def retrieve_nodes_by_name(self, names):
  107.         raise NotImplementedError
  108.  
  109.  
  110. class py2neoConnector(AbstractConnector):
  111.     def __init__(self, username, password, scheme='bolt', **kwargs):
  112.         self.name = f"py2neo-{scheme}"
  113.         self.connection = py2neo.Graph(auth=(username, password), scheme=scheme, **kwargs)
  114.  
  115.     def count_all(self):
  116.         return self.connection.run("MATCH (n) RETURN COUNT(*)").data()
  117.  
  118.     def retrieve_nodes_by_limit(self, limit):
  119.         return self.connection.run("MATCH (n:lexical_term) RETURN n LIMIT {limit}", {'limit': limit}).data()
  120.  
  121.     def retrieve_nodes_by_name(self, names):
  122.         transaction = self.connection.begin()
  123.         cursors = [
  124.             transaction.run("MATCH (n:lexical_term {name: {name}}) RETURN n", {'name': name})
  125.             for name in names
  126.         ]
  127.         # transaction.process()
  128.         transaction.commit()
  129.         return [cursor.data() for cursor in cursors]
  130.  
  131.  
  132. class Neo4jDriverConnector(AbstractConnector):
  133.     def __init__(self, username, password, **kwargs):
  134.         self.name = f"neo4j-driver"
  135.         self.connection = GraphDatabase.driver("bolt://localhost:7687", auth=(username, password))
  136.  
  137.     def count_all(self):
  138.         with self.connection.session() as session:
  139.             return session.run("MATCH (n) RETURN COUNT(*)").data()
  140.  
  141.     def retrieve_nodes_by_limit(self, limit):
  142.         with self.connection.session() as session:
  143.             return session.run("MATCH (n:lexical_term) RETURN n LIMIT {limit}", {'limit': limit}).data()
  144.  
  145.     def retrieve_nodes_by_name(self, names):
  146.         with self.connection.session() as session:
  147.             transaction = session.begin_transaction()
  148.             cursors = [
  149.                 transaction.run("MATCH (n:lexical_term {name: {name}}) RETURN n", {'name': name})
  150.                 for name in names
  151.             ]
  152.             transaction.sync()
  153.             transaction.close()
  154.             return [cursor.data() for cursor in cursors]
  155.  
  156.  
  157. if __name__ == '__main__':
  158.     TestRunner().run_tests()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement