Debian Codegraph @

docs/core/examples/bananabench.py

raw
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 import time
5 from io import BytesIO
6
7 from twisted.internet import protocol
8
9 # Twisted Imports
10 from twisted.spread import banana
11
12 iterationCount = 10000
13
14
15 class BananaBench:
16 r = range(iterationCount)
17
18 def setUp(self, encClass):
19 self.io = BytesIO()
20 self.enc = encClass()
21 self.enc.makeConnection(protocol.FileWrapper(self.io))
22 self.enc._selectDialect("none")
23 self.enc.expressionReceived = self.putResult
24
25 def putResult(self, result):
26 self.result = result
27
28 def tearDown(self):
29 self.enc.connectionLost()
30 del self.enc
31
32 def testEncode(self, value):
33 starttime = time.time()
34 for i in self.r:
35 self.enc.sendEncoded(value)
36 self.io.truncate(0)
37 endtime = time.time()
38 print(f" Encode took {endtime - starttime} seconds")
39 return endtime - starttime
40
41 def testDecode(self, value):
42 self.enc.sendEncoded(value)
43 encoded = self.io.getvalue()
44 starttime = time.time()
45 for i in self.r:
46 self.enc.dataReceived(encoded)
47 endtime = time.time()
48 print(f" Decode took {endtime - starttime} seconds")
49 return endtime - starttime
50
51 def performTest(self, method, data, encClass):
52 self.setUp(encClass)
53 method(data)
54 self.tearDown()
55
56 def runTests(self, testData):
57 print(f"Test data is: {testData}")
58 print(" Using Pure Python Banana:")
59 self.performTest(self.testEncode, testData, banana.Banana)
60 self.performTest(self.testDecode, testData, banana.Banana)
61
62
63 bench = BananaBench()
64 print(f"Doing {iterationCount} iterations of each test.")
65 print("")
66 testData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
67 bench.runTests(testData)
68 testData = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
69 bench.runTests(testData)
70 testData = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
71 bench.runTests(testData)
72 testData = [
73 b"one",
74 b"two",
75 b"three",
76 b"four",
77 b"five",
78 b"six",
79 b"seven",
80 b"eight",
81 b"nine",
82 b"ten",
83 ]
84 bench.runTests(testData)
85 testData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
86 bench.runTests(testData)
87 testData = [1, 2, [3, 4], [30.5, 40.2], 5, [b"six", b"seven", [b"eight", 9]], [10], []]
88 bench.runTests(testData)