Debian Codegraph @

bench/main.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2 # -*- coding: ascii -*-
3 u"""
4 =================================
5 Benchmark jsmin implementations
6 =================================
7
8 Benchmark jsmin implementations.
9
10 :Copyright:
11
12 Copyright 2011 - 2025
13 Andr\xe9 Malo or his licensors, as applicable
14
15 :License:
16
17 Licensed under the Apache License, Version 2.0 (the "License");
18 you may not use this file except in compliance with the License.
19 You may obtain a copy of the License at
20
21 http://www.apache.org/licenses/LICENSE-2.0
22
23 Unless required by applicable law or agreed to in writing, software
24 distributed under the License is distributed on an "AS IS" BASIS,
25 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26 See the License for the specific language governing permissions and
27 limitations under the License.
28
29 Usage::
30
31 python -mbench.main [-c COUNT] [-p file] jsfile ...
32
33 -c COUNT number of runs per jsfile and minifier. Defaults to 10.
34 -p file File to write the benchmark results in (pickled)
35
36 """
37 __author__ = u"Andr\xe9 Malo"
38 __version__ = "1.0.0"
39
40 import os as _os
41 import sys as _sys
42 import time as _time
43
44 cwd = _os.getcwd()
45 if cwd not in _sys.path:
46 _sys.path.append(cwd)
47
48
49 import_notes = []
50
51
52 class jsmins(object):
53 from bench import jsmin as p_01_simple_port
54
55 if _sys.version_info >= (2, 4):
56 from bench import jsmin_2_0_9 as p_02_jsmin_2_0_9
57 else:
58 import_notes.append(
59 "jsmin_2_0_9 available for python 2.4 and later..."
60 )
61 print(import_notes[-1])
62
63 import rjsmin as p_05_rjsmin
64
65 try:
66 import _rjsmin as p_06__rjsmin
67 except ImportError:
68 import_notes.append("_rjsmin (C-Port) not available")
69 print(import_notes[-1])
70
71
72 jsmins.p_05_rjsmin.jsmin = jsmins.p_05_rjsmin._make_jsmin(python_only=True)
73 print("Python Release: %s" % ".".join(map(str, _sys.version_info[:3])))
74 print("")
75
76
77 def slurp(filename):
78 """Load a file"""
79 fp = open(filename)
80 try:
81 return fp.read()
82 finally:
83 fp.close()
84
85
86 def print_(*value, **kwargs):
87 """Print stuff"""
88 (kwargs.get("file") or _sys.stdout).write(
89 "".join(value) + kwargs.get("end", "\n")
90 )
91
92
93 def bench(filenames, count):
94 """
95 Benchmark the minifiers with given javascript samples
96
97 :Parameters:
98 `filenames` : sequence
99 List of filenames
100
101 `count` : ``int``
102 Number of runs per js file and minifier
103
104 :Exceptions:
105 - `RuntimeError` : empty filenames sequence
106 """
107 if not filenames:
108 raise RuntimeError("Missing files to benchmark")
109 try:
110 xrange
111 except NameError:
112 xrange = range
113 try:
114 cmp
115 except NameError:
116 cmp = lambda a, b: (a > b) - (a < b)
117
118 ports = [item for item in dir(jsmins) if item.startswith("p_")]
119 ports.sort()
120 space = max(map(len, ports)) - 4
121 ports = [(item[5:], getattr(jsmins, item).jsmin) for item in ports]
122 flush = _sys.stdout.flush
123
124 struct = []
125 inputs = [(filename, slurp(filename)) for filename in filenames]
126 for filename, script in inputs:
127 print_("Benchmarking %r..." % filename, end=" ")
128 flush()
129 outputs = []
130 for _, jsmin in ports:
131 try:
132 outputs.append(jsmin(script))
133 except (SystemExit, KeyboardInterrupt):
134 raise
135 except:
136 outputs.append(None)
137 struct.append(
138 dict(
139 filename=filename,
140 sizes=[
141 (item is not None and len(item) or None)
142 for item in outputs
143 ],
144 size=len(script),
145 messages=[],
146 times=[],
147 )
148 )
149 print_("(%.1f KiB)" % (struct[-1]["size"] / 1024.0,))
150 flush()
151 times = []
152 for idx, (name, jsmin) in enumerate(ports):
153 if outputs[idx] is None:
154 print_(" FAILED %s" % (name,))
155 struct[-1]["times"].append((name, None))
156 else:
157 print_(
158 " Timing %s%s... (%5.1f KiB %s)"
159 % (
160 name,
161 " " * (space - len(name)),
162 len(outputs[idx]) / 1024.0,
163 idx == 0
164 and "*"
165 or ["=", ">", "<"][
166 cmp(len(outputs[idx]), len(outputs[0]))
167 ],
168 ),
169 end=" ",
170 )
171 flush()
172
173 xcount = count
174 while True:
175 counted = [None for _ in xrange(xcount)]
176 start = _time.time()
177 for _ in counted:
178 jsmin(script)
179 end = _time.time()
180 result = (end - start) * 1000
181 if result < 10: # avoid measuring within the error range
182 xcount *= 10
183 continue
184 times.append(result / xcount)
185 break
186
187 print_("%8.2f ms" % times[-1], end=" ")
188 flush()
189 if len(times) <= 1:
190 print_()
191 else:
192 print_(
193 "(factor: %s)"
194 % (
195 ", ".join(
196 [
197 "%.2f" % (timed / times[-1])
198 for timed in times[:-1]
199 ]
200 )
201 )
202 )
203 struct[-1]["times"].append((name, times[-1]))
204
205 flush()
206 print_()
207
208 return struct
209
210
211 def main(argv=None):
212 """Main"""
213 import getopt as _getopt
214 import os as _os
215 import pickle as _pickle
216
217 if argv is None:
218 argv = _sys.argv[1:]
219 try:
220 opts, args = _getopt.getopt(argv, "hc:p:", ["help"])
221 except getopt.GetoptError:
222 e = _sys.exc_info()[0](_sys.exc_info()[1])
223 print >> _sys.stderr, "%s\nTry %s -mbench.main --help" % (
224 e,
225 _os.path.basename(_sys.executable),
226 )
227 _sys.exit(2)
228
229 count, pickle = 10, None
230 for key, value in opts:
231 if key in ("-h", "--help"):
232 print >> _sys.stderr, (
233 "%s -mbench.main [-c count] [-p file] jsfile ..."
234 % (_os.path.basename(_sys.executable),)
235 )
236 _sys.exit(0)
237 elif key == "-c":
238 count = int(value)
239 elif key == "-p":
240 pickle = str(value)
241
242 struct = bench(args, count)
243 if pickle:
244 fp = open(pickle, "wb")
245 try:
246 fp.write(
247 _pickle.dumps(
248 (
249 ".".join(map(str, _sys.version_info[:3])),
250 import_notes,
251 struct,
252 ),
253 0,
254 )
255 )
256 finally:
257 fp.close()
258
259
260 if __name__ == "__main__":
261 main()