Main program, used when run as a script. The optional 'args' argument specifies the command line to be parsed, defaulting to sys.argv[1:]. The return value is an exit code to be passed to sys.exit(); it may be None to indicate success. When an exception happens during timing,
(args=None, *, _wrap_timer=None)
| 241 | |
| 242 | |
| 243 | def main(args=None, *, _wrap_timer=None): |
| 244 | """Main program, used when run as a script. |
| 245 | |
| 246 | The optional 'args' argument specifies the command line to be parsed, |
| 247 | defaulting to sys.argv[1:]. |
| 248 | |
| 249 | The return value is an exit code to be passed to sys.exit(); it |
| 250 | may be None to indicate success. |
| 251 | |
| 252 | When an exception happens during timing, a traceback is printed to |
| 253 | stderr and the return value is 1. Exceptions at other times |
| 254 | (including the template compilation) are not caught. |
| 255 | |
| 256 | '_wrap_timer' is an internal interface used for unit testing. If it |
| 257 | is not None, it must be a callable that accepts a timer function |
| 258 | and returns another timer function (used for unit testing). |
| 259 | """ |
| 260 | if args is None: |
| 261 | args = sys.argv[1:] |
| 262 | import getopt |
| 263 | try: |
| 264 | opts, args = getopt.getopt(args, "n:u:s:r:pvh", |
| 265 | ["number=", "setup=", "repeat=", |
| 266 | "process", "verbose", "unit=", "help"]) |
| 267 | except getopt.error as err: |
| 268 | print(err) |
| 269 | print("use -h/--help for command line help") |
| 270 | return 2 |
| 271 | |
| 272 | timer = default_timer |
| 273 | stmt = "\n".join(args) or "pass" |
| 274 | number = 0 # auto-determine |
| 275 | setup = [] |
| 276 | repeat = default_repeat |
| 277 | verbose = 0 |
| 278 | time_unit = None |
| 279 | units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0} |
| 280 | precision = 3 |
| 281 | for o, a in opts: |
| 282 | if o in ("-n", "--number"): |
| 283 | number = int(a) |
| 284 | if o in ("-s", "--setup"): |
| 285 | setup.append(a) |
| 286 | if o in ("-u", "--unit"): |
| 287 | if a in units: |
| 288 | time_unit = a |
| 289 | else: |
| 290 | print("Unrecognized unit. Please select nsec, usec, msec, or sec.", |
| 291 | file=sys.stderr) |
| 292 | return 2 |
| 293 | if o in ("-r", "--repeat"): |
| 294 | repeat = int(a) |
| 295 | if repeat <= 0: |
| 296 | repeat = 1 |
| 297 | if o in ("-p", "--process"): |
| 298 | timer = time.process_time |
| 299 | if o in ("-v", "--verbose"): |
| 300 | if verbose: |