Debian Codegraph @

bench/main.py

raw symbols ◀ ▶ SCIP
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 if _sys.version_info >= (2, 4):
54 from bench import jsmin_2_0_9 as p_02_jsmin_2_0_9
55 else:
56 import_notes.append(
57 "jsmin_2_0_9 available for python 2.4 and later..."
58 )
59 print(import_notes[-1])
60
61 import rjsmin as p_05_rjsmin
62
63 try:
64 import _rjsmin as p_06__rjsmin
65 except ImportError:
66 import_notes.append("_rjsmin (C-Port) not available")
67 print(import_notes[-1])
68
69
70 jsmins.p_05_rjsmin.jsmin = jsmins.p_05_rjsmin._make_jsmin(python_only=True)
71 print("Python Release: %s" % ".".join(map(str, _sys.version_info[:3])))
72 print("")
73
74
75 def slurp(filename):
76 """Load a file"""
77 fp = open(filename)
78 try:
79 return fp.read()
80 finally:
81 fp.close()
82
83
84 def print_(*value, **kwargs):
85 """Print stuff"""
86 (kwargs.get("file") or _sys.stdout).write(
87 "".join(value) + kwargs.get("end", "\n")
88 )
89
90
91 def bench(filenames, count):
92 """
93 Benchmark the minifiers with given javascript samples
94
95 :Parameters:
96 `filenames` : sequence
97 List of filenames
98
99 `count` : ``int``
100 Number of runs per js file and minifier
101
102 :Exceptions:
103 - `RuntimeError` : empty filenames sequence
104 """
105 if not filenames:
106 raise RuntimeError("Missing files to benchmark")
107 try:
108 xrange
109 except NameError:
110 xrange = range
111 try:
112 cmp
113 except NameError:
114 cmp = lambda a, b: (a > b) - (a < b)
115
116 ports = [item for item in dir(jsmins) if item.startswith("p_")]
117 ports.sort()
118 space = max(map(len, ports)) - 4
119 ports = [(item[5:], getattr(jsmins, item).jsmin) for item in ports]
120 flush = _sys.stdout.flush
121
122 struct = []
123 inputs = [(filename, slurp(filename)) for filename in filenames]
124 for filename, script in inputs:
125 print_("Benchmarking %r..." % filename, end=" ")
126 flush()
127 outputs = []
128 for _, jsmin in ports:
129 try:
130 outputs.append(jsmin(script))
131 except (SystemExit, KeyboardInterrupt):
132 raise
133 except:
134 outputs.append(None)
135 struct.append(
136 dict(
137 filename=filename,
138 sizes=[
139 (item is not None and len(item) or None)
140 for item in outputs
141 ],
142 size=len(script),
143 messages=[],
144 times=[],
145 )
146 )
147 print_("(%.1f KiB)" % (struct[-1]["size"] / 1024.0,))
148 flush()
149 times = []
150 for idx, (name, jsmin) in enumerate(ports):
151 if outputs[idx] is None:
152 print_(" FAILED %s" % (name,))
153 struct[-1]["times"].append((name, None))
154 else:
155 print_(
156 " Timing %s%s... (%5.1f KiB %s)"
157 % (
158 name,
159 " " * (space - len(name)),
160 len(outputs[idx]) / 1024.0,
161 idx == 0
162 and "*"
163 or ["=", ">", "<"][
164 cmp(len(outputs[idx]), len(outputs[0]))
165 ],
166 ),
167 end=" ",
168 )
169 flush()
170
171 xcount = count
172 while True:
173 counted = [None for _ in xrange(xcount)]
174 start = _time.time()
175 for _ in counted:
176 jsmin(script)
177 end = _time.time()
178 result = (end - start) * 1000
179 if result < 10: # avoid measuring within the error range
180 xcount *= 10
181 continue
182 times.append(result / xcount)
183 break
184
185 print_("%8.2f ms" % times[-1], end=" ")
186 flush()
187 if len(times) <= 1:
188 print_()
189 else:
190 print_(
191 "(factor: %s)"
192 % (
193 ", ".join(
194 [
195 "%.2f" % (timed / times[-1])
196 for timed in times[:-1]
197 ]
198 )
199 )
200 )
201 struct[-1]["times"].append((name, times[-1]))
202
203 flush()
204 print_()
205
206 return struct
207
208
209 def main(argv=None):
210 """Main"""
211 import getopt as _getopt
212 import os as _os
213 import pickle as _pickle
214
215 if argv is None:
216 argv = _sys.argv[1:]
217 try:
218 opts, args = _getopt.getopt(argv, "hc:p:", ["help"])
219 except getopt.GetoptError:
220 e = _sys.exc_info()[0](_sys.exc_info()[1])
221 print >> _sys.stderr, "%s\nTry %s -mbench.main --help" % (
222 e,
223 _os.path.basename(_sys.executable),
224 )
225 _sys.exit(2)
226
227 count, pickle = 10, None
228 for key, value in opts:
229 if key in ("-h", "--help"):
230 print >> _sys.stderr, (
231 "%s -mbench.main [-c count] [-p file] jsfile ..."
232 % (_os.path.basename(_sys.executable),)
233 )
234 _sys.exit(0)
235 elif key == "-c":
236 count = int(value)
237 elif key == "-p":
238 pickle = str(value)
239
240 struct = bench(args, count)
241 if pickle:
242 fp = open(pickle, "wb")
243 try:
244 fp.write(
245 _pickle.dumps(
246 (
247 ".".join(map(str, _sys.version_info[:3])),
248 import_notes,
249 struct,
250 ),
251 0,
252 )
253 )
254 finally:
255 fp.close()
256
257
258 if __name__ == "__main__":
259 main()