timeit — Measure execution time of small code snippets¶
This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times. See also Tim Peters’ introduction to the “Algorithms” chapter in the second edition of Python Cookbook, published by O’Reilly.
Basic Examples¶
The following example shows how the Command-Line Interface can be used to compare three different expressions:
This can be achieved from the Python Interface with:
A callable can also be passed from the Python Interface :
Note however that timeit() will automatically determine the number of repetitions only when the command-line interface is used. In the Examples section you can find more advanced examples.
Python Interface¶
The module defines three convenience functions and a public class:
timeit. timeit ( stmt=’pass’ , setup=’pass’ , timer=<default timer> , number=1000000 , globals=None ) ¶
Create a Timer instance with the given statement, setup code and timer function and run its timeit() method with number executions. The optional globals argument specifies a namespace in which to execute the code.
Changed in version 3.5: The optional globals parameter was added.
Create a Timer instance with the given statement, setup code and timer function and run its repeat() method with the given repeat count and number executions. The optional globals argument specifies a namespace in which to execute the code.
Changed in version 3.5: The optional globals parameter was added.
Changed in version 3.7: Default value of repeat changed from 3 to 5.
The default timer, which is always time.perf_counter() .
Changed in version 3.3: time.perf_counter() is now the default timer.
Class for timing execution speed of small code snippets.
The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to ‘pass’ ; the timer function is platform-dependent (see the module doc string). stmt and setup may also contain multiple statements separated by ; or newlines, as long as they don’t contain multi-line string literals. The statement will by default be executed within timeit’s namespace; this behavior can be controlled by passing a namespace to globals.
To measure the execution time of the first statement, use the timeit() method. The repeat() and autorange() methods are convenience methods to call timeit() multiple times.
The execution time of setup is excluded from the overall timed execution run.
The stmt and setup parameters can also take objects that are callable without arguments. This will embed calls to them in a timer function that will then be executed by timeit() . Note that the timing overhead is a little larger in this case because of the extra function calls.
Changed in version 3.5: The optional globals parameter was added.
Time number executions of the main statement. This executes the setup statement once, and then returns the time it takes to execute the main statement a number of times, measured in seconds as a float. The argument is the number of times through the loop, defaulting to one million. The main statement, the setup statement and the timer function to be used are passed to the constructor.
By default, timeit() temporarily turns off garbage collection during the timing. The advantage of this approach is that it makes independent timings more comparable. The disadvantage is that GC may be an important component of the performance of the function being measured. If so, GC can be re-enabled as the first statement in the setup string. For example:
Automatically determine how many times to call timeit() .
This is a convenience function that calls timeit() repeatedly so that the total time >= 0.2 second, returning the eventual (number of loops, time taken for that number of loops). It calls timeit() with increasing numbers from the sequence 1, 2, 5, 10, 20, 50, … until the time taken is at least 0.2 second.
If callback is given and is not None , it will be called after each trial with two arguments: callback(number, time_taken) .
New in version 3.6.
Call timeit() a few times.
This is a convenience function that calls the timeit() repeatedly, returning a list of results. The first argument specifies how many times to call timeit() . The second argument specifies the number argument for timeit() .
It’s tempting to calculate mean and standard deviation from the result vector and report these. However, this is not very useful. In a typical case, the lowest value gives a lower bound for how fast your machine can run the given code snippet; higher values in the result vector are typically not caused by variability in Python’s speed, but by other processes interfering with your timing accuracy. So the min() of the result is probably the only number you should be interested in. After that, you should look at the entire vector and apply common sense rather than statistics.
Changed in version 3.7: Default value of repeat changed from 3 to 5.
Helper to print a traceback from the timed code.
The advantage over the standard traceback is that source lines in the compiled template will be displayed. The optional file argument directs where the traceback is sent; it defaults to sys.stderr .
Command-Line Interface¶
When called as a program from the command line, the following form is used:
Where the following options are understood:
how many times to execute ‘statement’
how many times to repeat the timer (default 5)
statement to be executed once initially (default pass )
measure process time, not wallclock time, using time.process_time() instead of time.perf_counter() , which is the default
New in version 3.3.
specify a time unit for timer output; can select nsec , usec , msec , or sec
New in version 3.5.
print raw timing results; repeat for more digits precision
print a short usage message and exit
A multi-line statement may be given by specifying each line as a separate statement 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.
default_timer() measurements can be affected by other programs running on the same machine, so the best thing to do when accurate timing is necessary is to repeat the timing a few times and use the best time. The -r option is good for this; the default of 5 repetitions is probably enough in most cases. You can use time.process_time() to measure CPU time.
There is a certain baseline overhead associated with executing a pass statement. 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, and it might differ between Python versions.
Examples¶
It is possible to provide a setup statement that is executed only once at the beginning:
In the output, there are three fields. The loop count, which tells you how many times the statement body was run per timing loop repetition. The repetition count (‘best of 5’) which tells you how many times the timing loop was repeated, and finally the time the statement body took on average within the best repetition of the timing loop. That is, the time the fastest repetition took divided by the loop count.
The same can be done using the Timer class and its methods:
The following examples show how to time expressions that contain multiple lines. Here we compare the cost of using hasattr() vs. try / except to test for missing and present object attributes:
To give the timeit module access to functions you define, you can pass a setup parameter which contains an import statement:
Another option is to pass globals() to the globals parameter, which will cause the code to be executed within your current global namespace. This can be more convenient than individually specifying imports:
Create a Timer in Python: Step-by-Step Guide
Time tracking is critical to managing your projects. If you’re programming in Python, you’re in luck: The language gives you tools to build your own timers. A timer program can be useful for not only monitoring your own time, but measuring how long your Python program takes to run.
In this article, we’ll present two simple Python timers before looking at the modules you’ll need to create a timer program. We’ll then use these modules to build a stopwatch and a countdown timer, and show you how to measure a Python program’s execution time.
Understanding Timers in Python
A timer in Python is a time-tracking program. Python developers can create timers with the help of Python’s time modules. There are two basic types of timers: timers that count up and those that count down.
Stopwatches
Timers that count up from zero are frequently called stopwatches. We can use these to record the amount of time it takes to complete a task.
Runners often use stopwatch timers to record how long it takes them to complete a lap around a course or finish an entire run. You can use a stopwatch to track how long it takes to complete any task, such as coding a simple program.
Programmers often use stopwatch timers to compare the performance of various Python solutions. By seeing how long each solution takes to execute, you can choose the program that runs the fastest. Over time, this will allow you to better understand computational complexity and build intuition for choosing efficient solutions. These skills go a long way towards becoming a proficient programmer.
Countdown Timers
There are also countdown timers, set with a specific amount of time that depletes until the timer reaches zero. You can use Python to build countdown timers that serve different purposes.
For instance, you can build a cooking countdown timer to ensure you don’t leave food in the oven for too long. Countdown timers can also work to display the time remaining in a sporting event or during an exam. They are also used to count down the hours and minutes to a movie release or big event. The possibilities are endless!
Modules in Python
To create a simple timer in Python, you’ll need to call upon Python’s time and datetime modules.
Modules in Python are files that contain classes, functions, variables, and runnable code. By importing a module into your program, you can make use of each component inside the module.
The Python programming language has over 200 predefined modules within its standard library. You can even create your own modules to use in future programs.
The Python Time Module
One of the 200 modules in Python’s standard library is the time module. This module contains the functions we’ll need to build a simple timer in Python.
To use the time module in Python, we first import it into our program:
Listing modules at the beginning of a Python program makes the functions within the module available for use in our program. The time module holds more functions than we’ll cover here, but here are the most important ones:
The time.time() function
We call the time() function, located in the time module, as time.time() . The first time references the module, whereas the second is the function itself. The time() function returns the number of seconds that have passed since the epoch.
In the computing context, we refer to an “epoch” as the time according to which a computer calculates its timestamp values. Windows and most UNIX devices set the epoch as January 1, 1970 at 00:00:00.
When we use time.time() , we can see the amount of time that has passed since the epoch. We can even use time.ctime() to convert this number of seconds to the current local time. Take a look at this example:
In this example, we use time.time() to see how many seconds have elapsed since the epoch. We then convert this length of time to our current local time with time.ctime() . This program outputs the following information:
It has been over 1.5 billion seconds since the epoch.
The time.sleep() Function
The other function that we’ll need to build our timer is time.sleep() . This function creates a delay in a program that we can use to count time. time.sleep() takes a float argument representing the number of seconds that the program will pause for. Plug the example below into your Python integrated development environment (IDE) to see how time.delay() works:
Since we set time.sleep() to five seconds, the program idles for that length of time between outputs.
The Python Datetime Module
datetime is intended for manipulating dates. We’ll use this module to convert different timestamps into a common format that allows us to compare them.
The datetime.timedelta() Function
We can use timedelta() to express the difference between two dates and/or two times. In the example below, we use timedelta() to show the date one year from now:
timedelta() adds 365 days to the current date and outputs the date and time one year from now, down to the microsecond:
A Simple Lap Timer (Stopwatch)
Let’s use what we’ve learned to build a stopwatch. Our stopwatch is a lap timer that displays the time to complete a lap as well as total time. Check out the code below:
After importing the time module, we set time.time() to the start time of our timer. The stopwatch will count forward from this time. We use the variable lasttime to catalog each lap, whereas totaltime holds the value for the entire time the stopwatch runs. lapnum counts the number of laps we run. Finally, we set the value variable so the user can type “Q” or “q” to end the program.
Time increments in the background while we run the program. Each time the user presses the Enter key, the program displays their lap number, lap time, and total time. Even if you don’t need to record laps, you can still use this timer to track the total time you’re performing a task.
A Simple Countdown Timer
Let’s now build a countdown timer. This example incorporates both the datetime module and the time.sleep() function. Take a look at the program below:
Our countdown timer works by having a user input the number of hours, minutes, and seconds for the timer. You can find the code for these inputs at the bottom of the program below the countdown class.
The countdown class itself takes those inputs and converts them into a total number of seconds. As long as total_seconds is greater than zero, the while loop runs. Within the loop, we use the timedelta() function to calculate the time left on the timer.
The program prints the time left in hours:minutes:seconds format for the user to see. Immediately after, the program pauses for one second, reduces total_seconds by one second, and repeats the while loop. The loop continues until total_seconds reaches zero, at which point the program leaves the while loop and prints “Bzzzt! The countdown is at zero seconds!”
Measure Program Execution Time
You can use Python to measure the time it takes for a program to finish execution. This is not very different from what we’ve already done before: We define a starting point, run the program whose time we want to measure, and specify the time at which the program finishes execution. We get the program’s execution time by subtracting the start time point from the end time point.
Let’s compare a few solutions for finding an element within a list. We’ll create a list of 10,000,000 elements and see how long it takes each solution to find the number 700,000.
First, we’ll build a program that makes random guesses until it finds the answer.
The program took 16 seconds to find the element; that’s clearly no good.
Let’s try a better approach. This time, instead of making random guesses, the program will make one pass through the list to look for the element.
This program took only 0.6 seconds. That’s a lot better.
Let’s see if we can beat this time with a more sophisticated algorithm called “binary search.” We borrow the code for the algorithm from this GitHub page.
With only 0.1 seconds required to find the element, we’ve found the winning solution!
These examples show the importance of time-tracking if you’re looking to build scalable programs. When you build a program that ends up being used by many people, every fraction of a second saved on computation time helps.
Start Your Python Journey With Udacity
In this article, we explored the time and datetime modules to understand how time works in Python. We used this knowledge to create a lap timer, a countdown timer, and showed you how to measure the execution time of Python programs.
Want to go beyond building timers and dive into fields like app development, machine learning, and data science?
Take your first step by enrolling in Udacity’s Introduction to Programming Nanodegree.
Создайте таймер обратного отсчета в Python
В этом руководстве рассказывается, как создать таймер обратного отсчета в Python.
Код принимает ввод того, как долго должен быть обратный отсчет, и начинает обратный отсчет сразу после ввода ввода.
Использование модуля time и функции sleep() для создания таймера обратного отсчета в Python
Модуль time — это общий модуль Python, содержащий вспомогательные функции и переменные, связанные со временем. Основная функция, используемая в этом руководстве, — это функция sleep() , которая представляет собой асинхронную функцию, которая приостанавливает выполнение одного потока на n секунд.
Если ваша программа однопоточная, как в этом руководстве, то функция sleep() остановит выполнение всей программы до тех пор, пока не будет достигнуто заданное время. Благодаря этому, наряду с подтвержденным пользовательским вводом, мы можем создать простой таймер обратного отсчета в Python.
Первое, что нужно сделать, это импортировать модуль time для использования функции sleep() .
Затем объявите функцию, которая будет работать как таймер обратного отсчета. Назовем эту функцию countdown() . Функция принимает единственный параметр: количество секунд ( num_of_secs ), до которого будет отсчитывать таймер.
Переменная num_of_secs будет непрерывно уменьшаться в цикле, пока не достигнет 0 (что переводится в False и завершает цикл без каких-либо дополнительных условий).
Внутри цикла отформатируйте входную переменную num_of_secs в формат MM:SS и распечатайте ее каждый раз, когда она уменьшается. Для этого используйте встроенную функцию Python divmod() , которая принимает два числа и возвращает произведение и остаток от двух чисел соответственно. Затем отформатируйте результат кортежа divmod() в формат MM:SS с помощью встроенной строковой функции format() .
<:02d>форматирует аргумент в 2-значное целое число (из-за символа 02d ). Если целое число меньше двух цифр, к нему добавляются ведущие 0 .
Тайминг в Python
Python – язык программирования, который можно отнести к общему назначению. С его помощью пишут как бизнес-софт, так и развлекательный (игровой) контент. Это отличное решение для новичков в разработке. Относится к объектно-ориентированному типу.
В данной статье будет рассказано о том, что собой представляет задержка в Python, как использовать time (таймер), для чего все это нужно. Информация пригодится даже опытным разработчикам, которые планируют работу со временем в будущей утилите.
Ключевые термины
Пытаясь освоить Python, программеру потребуется выучить немало теории. Вот базовые термины, без которых время и остальные компоненты кодификаций применять на деле не получится:
- Ключевое слово – зарезервированное системой слово или фраза. Обозначает действие, операцию, функцию. Ключевики не могут выступать в виде имен переменных.
- Переменная – именованная ячейка памяти, которую можно изменять, сохранять и считывать.
- Алгоритм – последовательность действий, набор правил, помогающих решать те или иные задачи.
- Класс – набор связанных между собой объектов, которые имеют общие свойства.
- Объект – комбинация переменных, констант и иных структурных единиц. Они выбираются совместно и аналогичным образом проходят обработку.
- Константа – значение, которое не будет меняться на протяжении всего выполнения утилиты.
- Тип данных – классификация информации определенного вида.
- Массив – множество данных. Они предварительно группируются.
Огромную роль в Python играют ключевые слова. Их необходимо либо запоминать, либо заучивать, либо держать где-то поблизости справочник с соответствующими данными. Иначе при объявлении переменных не исключены проблемы.
Задержка – это…
Задержка – термин, который применим ко времени. Он встречается и в обыденной жизни. Это – ситуация, когда что-то происходит или должно осуществиться не сразу. Пример – после наступления каких-то обстоятельств.
В программировании задержка «откладывает» выполнение кода на определенное время. Часто такая потребность возникает тогда, когда нужно дождаться завершения иного процесса, чтобы задействовать далее полученный результат.
При рассмотрении многопоточных утилит, использовать таймер (timer) и время (time) нужно, чтобы дождаться завершения операции и функций из других потоков.
Класс Timer
Класс Timer () в Python отвечает за время и работу с ним «от начала по конца». Модуль, метод, используемый для задержки и всего, что с ней связано. Перед использованием оного требуется произвести импорт компонента.
Для этого подойдет запись типа import time в Python. Класс относится к модулю threading. Он создает таймер, который запускает функцию с аргументами и ключевыми значениями (kwargs). Происходит это за счет time, установленного как interval. Этот параметр указывается в секундах.
Программеру предстоит запомнить следующее:
- Запись функции с классом, отвечающего за таймаут (timeout) –
- Если args равен None (этот показатель устанавливается изначально), Python использует пустой список.
- Когда ключевое слово kwargs равен None, применяется пустой словарь.
- Класс «Таймер» представлен действием, которое нужно запускать только по прошествии конкретного промежутка времени.
- Таймер выступает в виде подкласса threading.Thread().
Все это требуется запомнить. А еще – учесть, что в процессе коддинга предстоит использовать суперкласс (super class), а также мета данные.
Функции
Рассматривая methods time, программисту требуется изучить разнообразные функции, связанные со временем. Это поможет лучше разобраться в потоках и задержках. Не стоит забывать, что при тестинге важно использовать print. Эта операция выводит результат на экран.
Time.Time
Функция Time() будет возвращать число секунд, которые прошли с начала эпохи. Для Unix-систем это – 1.01.1970. Отсчет с 12 часов ночи ровно.
Ctime()
Компонент, который будет в виде аргумента в Python принимать количество секунд, прошедших с самого начала эпохи. Результат – возврат строки по местному time.
Sleep
Отвечает за непосредственную задержку. Откладывает исполнение нынешнего потока на заданное количество секунд.
Класс struct_time
Изучая, какой метод подойдет для работы с таймерами и super class, стоит обратить внимание на struct_time. Этот объект может быть принят некоторыми функциями в упомянутом ранее модуле. При обработке оного происходит возврат.
Выше – наглядный пример.
Реализация Sleep
Когда нужный метод для работы с задержкой изучен, можно рассмотреть то, как сделать таймаут. Для этого используют super class, а также sleep. Он проходит реализацию несколькими способами:
- Через time.sleep(). Это – встроенная возможность Python. Отвечает за таймаут через модуль time. Откладывает выполнение потока на установленное количество секунд.
- Вызов с декораторами. Активируют, когда одно неудачно выполненное действие требуется запустить снова.
- В потоках. Такие ситуации требуют, чтобы приложение избегало простоя. Для этого применяют или time.sleep(), или Event.wait() из модуля threading.
- Из Async IO. Асинхронные возможности появились в Питоне, начиная с 3.4 версии. Это – тип параллельного программирования.
- В Tkinter и wxPython. Отсрочки возможны при создании пользовательских интерфейсов. При применении sleep() внутри GUI кода блокируется цикл обработки событий.
- After(). Это – метод, который погружает в сон для Tkinter. Часть стандартной библиотеки.
- CallLater. Метод для wxPython. Имеет больше виджетов и хорошо годится для нативной разработки.
А вот видео, где можно наглядно увидеть работу с таймером в Python. Лучше разобраться с этой темой, как и с языком программирования, помогут дистанционные компьютерные курсы. Программы рассчитаны на срок до года. В конце будет выдан электронный сертификат. В процессе пользователи получат не только хорошо поданный учебный материал, но и новые полезные связи. А еще – соберут портфолио для трудоустройства.