- 
          
- 
                Notifications
    You must be signed in to change notification settings 
- Fork 33.3k
          gh-137944: use argparse instead of getopt in timeit
          #137955
        
          New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Closed
      
      
    
  
     Closed
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            5 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      
    File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
|  | @@ -6,34 +6,7 @@ | |
|  | ||
| Library usage: see the Timer class. | ||
|  | ||
| Command line usage: | ||
| python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement] | ||
|  | ||
| Options: | ||
| -n/--number N: how many times to execute 'statement' (default: see below) | ||
| -r/--repeat N: how many times to repeat the timer (default 5) | ||
| -s/--setup S: statement to be executed once initially (default 'pass'). | ||
| Execution time of this setup statement is NOT timed. | ||
| -p/--process: use time.process_time() (default is time.perf_counter()) | ||
| -v/--verbose: print raw timing results; repeat for more digits precision | ||
| -u/--unit: set the output time unit (nsec, usec, msec, or sec) | ||
| -h/--help: print this usage message and exit | ||
| --: separate options from statement, use when statement starts with - | ||
| statement: statement to be timed (default 'pass') | ||
|  | ||
| A multi-line statement may be given by specifying each line as a | ||
| separate argument; indented lines are possible by enclosing an | ||
| argument in quotes and using leading spaces. Multiple -s options are | ||
| treated similarly. | ||
|  | ||
| If -n is not given, a suitable number of loops is calculated by trying | ||
| increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the | ||
| total time is at least 0.2 seconds. | ||
|  | ||
| Note: there is a certain baseline overhead associated with executing a | ||
| pass statement. It differs between versions. The code here doesn't try | ||
| to hide it, but you should be aware of it. The baseline overhead can be | ||
| measured by invoking the program without arguments. | ||
| Command line usage: python -m timeit --help | ||
|  | ||
| Classes: | ||
|  | ||
|  | @@ -240,6 +213,71 @@ def repeat(stmt="pass", setup="pass", timer=default_timer, | |
| return Timer(stmt, setup, timer, globals).repeat(repeat, number) | ||
|  | ||
|  | ||
| def _make_parser(): | ||
| import argparse | ||
|  | ||
| parser = argparse.ArgumentParser( | ||
| description="""\ | ||
| Tool avoiding a number of common traps for measuring execution times. | ||
| See also Tim Peters' introduction to the Algorithms chapter in the | ||
| Python Cookbook, published by O'Reilly.""", | ||
| epilog="""\ | ||
| A multi-line statement may be given by specifying each line as a | ||
| separate argument; indented lines are possible by enclosing an | ||
| argument in quotes and using leading spaces. Multiple -s options are | ||
| treated similarly. | ||
|  | ||
| Use "--" to separate command-line options from actual statements, | ||
| or when a statement starts with '-'. | ||
|  | ||
| If -n is not given, a suitable number of loops is calculated by trying | ||
| increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the | ||
| total time is at least 0.2 seconds. | ||
|  | ||
| Note: there is a certain baseline overhead associated with executing a | ||
| pass statement. It differs between versions. The code here doesn't try | ||
| to hide it, but you should be aware of it. The baseline overhead can be | ||
| measured by invoking the program without arguments.""", | ||
| formatter_class=argparse.RawTextHelpFormatter, | ||
| allow_abbrev=False, | ||
| ) | ||
| # use a group to avoid rendering a 'positional arguments' section | ||
| group = parser.add_argument_group() | ||
| group.add_argument( | ||
| "-n", "--number", metavar="N", default=0, type=int, | ||
| help="how many times to execute 'statement' (default: see below)", | ||
| ) | ||
| group.add_argument( | ||
| "-r", "--repeat", type=int, metavar="N", default=default_repeat, | ||
| help="how many times to repeat the timer (default: 5)", | ||
| ) | ||
| group.add_argument( | ||
| "-s", "--setup", action="append", metavar="S", default=[], | ||
| help="statement to be executed once initially (default: 'pass').\n" | ||
| "Execution time of this setup statement is NOT timed.", | ||
| ) | ||
| group.add_argument( | ||
| "-u", "--unit", choices=["nsec", "usec", "msec", "sec"], metavar="U", | ||
| help="set the output time unit (nsec, usec, msec, or sec)", | ||
| ) | ||
| group.add_argument( | ||
| "-p", "--process", action="store_true", | ||
| help="use time.process_time() (default: time.perf_counter())", | ||
| ) | ||
| group.add_argument( | ||
| "-v", "--verbose", action="count", default=0, | ||
| help="print raw timing results; repeat for more digits precision", | ||
| ) | ||
| # Use argparse.REMAINDER to ignore option-like argument found at the end. | ||
| # If '--' is being specified as the "first" statement, it will be ignored | ||
| # and used to separate the options from the list of statements. | ||
| group.add_argument( | ||
| "statement", nargs=argparse.REMAINDER, | ||
| help="statement to be timed (default: 'pass')", | ||
| ) | ||
| return parser | ||
|  | ||
|  | ||
| def main(args=None, *, _wrap_timer=None): | ||
| """Main program, used when run as a script. | ||
|  | ||
|  | @@ -257,53 +295,18 @@ def main(args=None, *, _wrap_timer=None): | |
| is not None, it must be a callable that accepts a timer function | ||
| and returns another timer function (used for unit testing). | ||
| """ | ||
| if args is None: | ||
| args = sys.argv[1:] | ||
| import getopt | ||
| try: | ||
| opts, args = getopt.getopt(args, "n:u:s:r:pvh", | ||
| ["number=", "setup=", "repeat=", | ||
| "process", "verbose", "unit=", "help"]) | ||
| except getopt.error as err: | ||
| print(err) | ||
| print("use -h/--help for command line help") | ||
| return 2 | ||
|  | ||
| timer = default_timer | ||
| stmt = "\n".join(args) or "pass" | ||
| number = 0 # auto-determine | ||
| setup = [] | ||
| repeat = default_repeat | ||
| verbose = 0 | ||
| time_unit = None | ||
| units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0} | ||
| precision = 3 | ||
| for o, a in opts: | ||
| if o in ("-n", "--number"): | ||
| number = int(a) | ||
| if o in ("-s", "--setup"): | ||
| setup.append(a) | ||
| if o in ("-u", "--unit"): | ||
| if a in units: | ||
| time_unit = a | ||
| else: | ||
| print("Unrecognized unit. Please select nsec, usec, msec, or sec.", | ||
| file=sys.stderr) | ||
| return 2 | ||
| if o in ("-r", "--repeat"): | ||
| repeat = int(a) | ||
| if repeat <= 0: | ||
| repeat = 1 | ||
| if o in ("-p", "--process"): | ||
| timer = time.process_time | ||
| if o in ("-v", "--verbose"): | ||
| if verbose: | ||
| precision += 1 | ||
| verbose += 1 | ||
| if o in ("-h", "--help"): | ||
| print(__doc__, end="") | ||
| return 0 | ||
| setup = "\n".join(setup) or "pass" | ||
| parser = _make_parser() | ||
| args = parser.parse_args(args) | ||
|  | ||
| setup = "\n".join(args.setup) or "pass" | ||
| if args.statement and args.statement[0] == '--': | ||
| args.statement.pop(0) | ||
| stmt = "\n".join(args.statement) or "pass" | ||
|         
                  picnixz marked this conversation as resolved.
              Show resolved
            Hide resolved | ||
| timer = time.process_time if args.process else default_timer | ||
| number = args.number # will be deduced if 0 | ||
| repeat = max(1, args.repeat) | ||
| verbose = bool(args.verbose) | ||
| precision = 3 + max(0, args.verbose - 1) | ||
|  | ||
| # Include the current directory, so that local imports work (sys.path | ||
| # contains the directory of this script, rather than the current | ||
|  | @@ -338,14 +341,16 @@ def callback(number, time_taken): | |
| t.print_exc() | ||
| return 1 | ||
|  | ||
| units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0} | ||
| scales = [(scale, unit_name) for unit_name, scale in units.items()] | ||
| scales.sort(reverse=True) | ||
|  | ||
| def format_time(dt): | ||
| unit = time_unit | ||
| unit = args.unit | ||
|  | ||
| if unit is not None: | ||
| scale = units[unit] | ||
| else: | ||
| scales = [(scale, unit) for unit, scale in units.items()] | ||
| scales.sort(reverse=True) | ||
| 
      Comment on lines
    
      -347
     to 
      -348
    
   There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FTR, this is constant for each invokation, so I can move it outside the function definition. | ||
| for scale, unit in scales: | ||
| if dt >= scale: | ||
| break | ||
|  | @@ -362,7 +367,6 @@ def format_time(dt): | |
| % (number, 's' if number != 1 else '', | ||
| repeat, format_time(best))) | ||
|  | ||
| best = min(timings) | ||
| There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. FTR,  | ||
| worst = max(timings) | ||
| if worst >= best * 4: | ||
| import warnings | ||
|  | @@ -371,7 +375,7 @@ def format_time(dt): | |
| "slower than the best time (%s)." | ||
| % (format_time(worst), format_time(best)), | ||
| UserWarning, '', 0) | ||
| return None | ||
| return 0 | ||
|  | ||
|  | ||
| if __name__ == "__main__": | ||
|  | ||
        
          
          
            3 changes: 3 additions & 0 deletions
          
          3 
        
  Misc/NEWS.d/next/Library/2025-08-19-14-52-27.gh-issue-137944.gAFxTV.rst
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| Improve :ref:`command-line interface <timeit-command-line-interface>` for | ||
| :mod:`timeit`. The ``--help`` option now shows a colored help by default. | ||
| Patch by Bénédikt Tran. | 
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.