zaro

How to See Execution Time in VS Code Python?

Published in Python Timing 2 mins read

To measure execution time in VS Code Python, you can leverage the timeit module.

Measuring Execution Time with timeit

The timeit module in Python provides a simple way to measure the execution time of small code snippets. Here's how you can use it, with an emphasis on using timeit() as the core method:

Using timeit()

  • The timeit() method is the primary tool for measuring execution time. It takes a statement (code snippet) as input and executes it multiple times, returning the total time taken.

  • Example:

    import timeit
    
    # Code snippet to time
    my_code = """
    sum([i for i in range(10000)])
    """
    
    # Measure execution time of my_code
    execution_time = timeit.timeit(stmt=my_code, number=100)
    print(f"Execution time: {execution_time:.6f} seconds")

    This code snippet will execute the list comprehension and summing operation 100 times and output the total execution time.

Using repeat() and autorange()

While not strictly necessary, the repeat() and autorange() methods can be useful for more sophisticated timing:

  • repeat(): This allows you to call timeit() multiple times, providing a list of execution times which can be useful for seeing variation.

    import timeit
    
    my_code = """
    sum([i for i in range(10000)])
    """
    
    times = timeit.repeat(stmt=my_code, repeat=3, number=100)
    print(f"Times: {times}")
    print(f"Minimum time: {min(times):.6f} seconds")
    
  • autorange(): This automatically determines an appropriate number of iterations to get a reliable timing measure.

Understanding Setup

  • The timeit module allows you to specify a setup parameter. Code in this parameter is executed only once before timing begins.

  • This is useful for operations such as importing libraries or initializing variables.

  • The execution time of the setup is excluded from the timed run.

    import timeit
    
    setup_code = """
    my_list = list(range(10000))
    """
    my_code = """
    sum(my_list)
    """
    
    execution_time = timeit.timeit(stmt=my_code, setup=setup_code, number=100)
    print(f"Execution time: {execution_time:.6f} seconds")

Practical Insights

  • When timing code, it's best practice to use a number of iterations greater than one to get a more consistent average execution time, as a single run may be affected by system load.
  • Use timeit.repeat() to see variations in execution time, and then average these results.
  • Remember, the timeit module focuses on timing small pieces of code, not an entire program.

By incorporating these methods, you can effectively measure execution time in your Python projects within VS Code.