Debian Codegraph @

docs/core/benchmarks/netstringreceiver.py

raw
1 # Copyright (c) Twisted Matrix Laboratories.
2 # See LICENSE for details.
3
4 import gc
5 import math
6 import os
7 import sys
8 import time
9
10 from twisted.protocols.test import test_basic
11 from twisted.python.compat import range, raw_input
12 from twisted.test import proto_helpers
13
14 NETSTRING_POSTFIX = b","
15 USAGE = """\
16 Usage: %s <number> <filename>
17
18 This script creates up to 2 ** <number> chunks with up to 2 **
19 <number> characters and sends them to the NetstringReceiver. The
20 sorted performance data for all combination is written to <filename>
21 afterwards.
22
23 You might want to start with a small number, maybe 10 or 12, and slowly
24 increase it. Stop when the performance starts to deteriorate ;-).
25 """
26
27
28 class PerformanceTester:
29 """
30 A class for testing the performance of some
31 """
32
33 headers = []
34 lineFormat = ""
35 performanceData = {}
36
37 def __init__(self, filename):
38 """
39 Initializes C{self.filename}.
40
41 If a file with this name already exists, asks if it should be
42 overwritten. Terminates with exit status 1, if the user does
43 not accept.
44 """
45 if os.path.isfile(filename):
46 response = raw_input(
47 ("A file named %s exists. " "Overwrite it (y/n)? ") % filename
48 )
49 if response.lower() != "y":
50 print("Performance test cancelled.")
51 sys.exit(1)
52 self.filename = filename
53
54 def testPerformance(self, number):
55 """
56 Drives the execution of C{performTest} with arguments between
57 0 and C{number - 1}.
58
59 @param number: Defines the number of test runs to be performed.
60 @type number: C{int}
61 """
62 for iteration in range(number):
63 self.performTest(iteration)
64
65 def performTest(self, iteration):
66 """
67 Performs one test iteration. Overwrite this.
68
69 @param iteration: The iteration number. Can be used to configure
70 the test.
71 @type iteration: C{int}
72 @raise NotImplementedError: because this method has to be implemented
73 by the subclass.
74 """
75 raise NotImplementedError
76
77 def createReport(self):
78 """
79 Creates a file and writes a table with performance data.
80
81 The performance data are ordered by the total size of the netstrings.
82 In addition they show the chunk size, the number of chunks and the
83 time (in seconds) that elapsed while the C{NetstringReceiver}
84 received the netstring.
85
86 @param filename: The name of the report file that will be written.
87 @type filename: C{str}
88 """
89 self.outputFile = open(self.filename, "w")
90 self.writeHeader()
91 self.writePerformanceData()
92 self.writeLineSeparator()
93 print("The report was written to %s." % self.filename)
94
95 def writeHeader(self):
96 """
97 Writes the table header for the report.
98 """
99 self.writeLineSeparator()
100 self.outputFile.write("| {} |\n".format(" | ".join(self.headers)))
101 self.writeLineSeparator()
102
103 def writeLineSeparator(self):
104 """
105 Writes a 'line separator' made from '+' and '-' characters.
106 """
107 dashes = ("-" * (len(header) + 2) for header in self.headers)
108 self.outputFile.write("+%s+\n" % "+".join(dashes))
109
110 def writePerformanceData(self):
111 """
112 Writes one line for each item in C{self.performanceData}.
113 """
114 for combination, elapsed in sorted(self.performanceData.items()):
115 totalSize, chunkSize, numberOfChunks = combination
116 self.outputFile.write(
117 self.lineFormat % (totalSize, chunkSize, numberOfChunks, elapsed)
118 )
119
120
121 class NetstringPerformanceTester(PerformanceTester):
122 """
123 A class for determining the C{NetstringReceiver.dataReceived} performance.
124
125 Instantiates a C{NetstringReceiver} and calls its
126 C{dataReceived()} method with different chunks sizes and numbers
127 of chunks. Presents a table showing the relation between input
128 data and time to process them.
129 """
130
131 headers = ["Chunk size", "Number of chunks", "Total size", "Time to receive"]
132 lineFormat = "| %%%dd | %%%dd | %%%dd | %%%d.4f |\n" % tuple(
133 len(header) for header in headers
134 )
135
136 def __init__(self, filename):
137 """
138 Sets up the output file and the netstring receiver that will be
139 used for receiving data.
140
141 @param filename: The name of the file for storing the report.
142 @type filename: C{str}
143 """
144 PerformanceTester.__init__(self, filename)
145 transport = proto_helpers.StringTransport()
146 self.netstringReceiver = test_basic.TestNetstring()
147 self.netstringReceiver.makeConnection(transport)
148
149 def performTest(self, number):
150 """
151 Tests the performance of C{NetstringReceiver.dataReceived}.
152
153 Feeds netstrings of various sizes in different chunk sizes
154 to a C{NetstringReceiver} and stores the elapsed time in
155 C{self.performanceData}.
156
157 @param number: The maximal chunks size / number of
158 chunks to be checked.
159 @type number: C{int}
160 """
161 chunkSize = 2**number
162 numberOfChunks = chunkSize
163 while numberOfChunks:
164 self.testCombination(chunkSize, numberOfChunks)
165 numberOfChunks = numberOfChunks // 2
166
167 def testCombination(self, chunkSize, numberOfChunks):
168 """
169 Tests one combination of chunk size and number of chunks.
170
171 @param chunkSize: The size of one chunk to be sent to the
172 C{NetstringReceiver}.
173 @type chunkSize: C{int}
174 @param numberOfChunks: The number of C{chunkSize}-sized chunks to
175 be sent to the C{NetstringReceiver}.
176 @type numberOfChunks: C{int}
177 """
178 chunk, dataSize = self.configureCombination(chunkSize, numberOfChunks)
179 elapsed = self.receiveData(chunk, numberOfChunks, dataSize)
180 key = (chunkSize, numberOfChunks, dataSize)
181 self.performanceData[key] = elapsed
182
183 def configureCombination(self, chunkSize, numberOfChunks):
184 """
185 Updates C{MAX_LENGTH} for {self.netstringReceiver} (to avoid
186 C{NetstringParseErrors} that might be raised if the size
187 exceeds the default C{MAX_LENGTH}).
188
189 Calculates and returns one 'chunk' of data and the total size
190 of the netstring.
191
192 @param chunkSize: The size of chunks that will be received.
193 @type chunkSize: C{int}
194 @param numberOfChunks: The number of C{chunkSize}-sized chunks
195 that will be received.
196 @type numberOfChunks: C{int}
197
198 @return: A tuple consisting of string of C{chunkSize} 'a'
199 characters and the size of the netstring data portion.
200 """
201 chunk = b"a" * chunkSize
202 dataSize = chunkSize * numberOfChunks
203 self.netstringReceiver.MAX_LENGTH = dataSize
204 numberOfDigits = math.ceil(math.log10(dataSize)) + 1
205 return chunk, dataSize
206
207 def receiveData(self, chunk, numberOfChunks, dataSize):
208 dr = self.netstringReceiver.dataReceived
209 now = time.time()
210 dr(f"{dataSize}:".encode("ascii"))
211 for idx in range(numberOfChunks):
212 dr(chunk)
213 dr(NETSTRING_POSTFIX)
214 elapsed = time.time() - now
215 assert self.netstringReceiver.received, "Didn't receive string!"
216 return elapsed
217
218
219 def disableGarbageCollector():
220 gc.disable()
221 print("Disabled Garbage Collector.")
222
223
224 def main(number, filename):
225 disableGarbageCollector()
226 npt = NetstringPerformanceTester(filename)
227 npt.testPerformance(int(number))
228 npt.createReport()
229
230
231 if __name__ == "__main__":
232 if len(sys.argv) < 3:
233 print(USAGE % sys.argv[0])
234 sys.exit(1)
235 main(*sys.argv[1:3])