- How do you determine a processing time in Python?
- 9 Answers 9
- See also:
- Как посчитать время программы? python
- 2 ответа 2
- Как измерить время выполнения функции в Python
- Использование модуля time
- Использование функции time.perf_counter
- Использование функции time.process_time
- Использование модуля timeit
- Использование декораторов для измерения времени выполнения
- Заключение
How do you determine a processing time in Python?
I’m new to Python, and confused by the date/time documentation. I want to compute the time that it takes to perform a computation. In java, I would write:
long timeBefore = System.currentTimeMillis(); doStuff(); long timeAfter = System.currentTimeMillis(); elapsed time = timeAfter - timeBefore;
I wasn’t looking at Python code, I was preparing to write it. By the way, I’m intrigued by your Building Skills in Python book, I’ll be checking it out.
9 Answers 9
Equivalent in python would be:
>>> import time >>> tic = time.clock() >>> toc = time.clock() >>> toc - tic
If you are trying to find the best performing method then you should probably have a look at timeit .
Thanks for providing the equivalent. I’ll have to look into timeit in the future, but for my current small exercise this will be sufficient.
Note that time.clock doesn’t do the same on all platforms. More notably, on unix it returns processor time, not clock time.
time.clock() is deprecated since Python 3.3 and prints a warning since Python 3.7. The recommended functions are now time.process_time() and time.perf_counter() . See docs.python.org/3/library/time.html#time.clock
Can this answer please be updated for python >=3.3? Please replace time.clock() with .perf_counter() or .process_time()
Building on and updating a number of earlier responses (thanks: SilentGhost, nosklo, Ramkumar) a simple portable timer would use timeit ‘s default_timer() :
>>> import timeit >>> tic=timeit.default_timer() >>> # Do Stuff >>> toc=timeit.default_timer() >>> toc - tic #elapsed time in seconds
This will return the elapsed wall clock (real) time, not CPU time. And as described in the timeit documentation chooses the most precise available real-world timer depending on the platform.
ALso, beginning with Python 3.3 this same functionality is available with the time.perf_counter performance counter. Under 3.3+ timeit.default_timer() refers to this new counter.
For more precise/complex performance calculations, timeit includes more sophisticated calls for automatically timing small code snippets including averaging run time over a defined set of repetitions.
You can implement two tic() and tac() functions, where tic() captures the time which it is called, and tac() prints the time difference since tic() was called. Here is a short implementation:
import time _start_time = time.time() def tic(): global _start_time _start_time = time.time() def tac(): t_sec = round(time.time() - _start_time) (t_min, t_sec) = divmod(t_sec,60) (t_hour,t_min) = divmod(t_min,60) print('Time passed: <>hour:<>min:<>sec'.format(t_hour,t_min,t_sec))
Now in your code you can use it as:
and it will, for example, output:
Time passed: 0hour:7min:26sec
See also:
For Python 3.3 and later time.process_time() is very nice:
import time t = time.process_time() #do some stuff elapsed_time = time.process_time() - t
Note this ignores any time.sleep() time delays in the code, I just tried testing it with time.sleep() for a minute and got quite confused! E.g. if you want to repeat the process at precise time intervals like webscraping, can measure elapsed_time then add on appropriate time.sleep() delay
Spoke too soon, Actually I just used selenium package to open website login, send message, can see it’s taking 20 seconds or more just for selenium to fill out the message in text box, but get 0.125 as the elapsed time from process_time() before getting the URL to time at end typing message, not sure what’s going on, docs mentions time.sleep() delays ignored by process_time, but filling the box is normal processing time surely, sending several send_keys() calls from selenium to do this.
@WillCroxford I encountered similar with process_time(). time() gave a more accurate number for the wait I experienced before my functions executed.
I also got a requirement to calculate the process time of some code lines. So I tried the approved answer and I got this warning.
DeprecationWarning: time.clock has been deprecated in Python 3.3 and will be removed from Python 3.8: use time.perf_counter or time.process_time instead
So python will remove time.clock() from Python 3.8. You can see more about it from issue #13270. This warning suggest two function instead of time.clock(). In the documentation also mention about this warning in-detail in time.clock() section.
Deprecated since version 3.3, will be removed in version 3.8: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.
Let’s look at in-detail both functions.
Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
New in version 3.3.
Changed in version 3.10: On Windows, the function is now system-wide.
So if you want it as nanoseconds , you can use time.perf_counter_ns() and if your code consist with time.sleep(secs), it will also count. Ex:-
import time def func(x): time.sleep(5) return x * x lst = [1, 2, 3] tic = time.perf_counter() print([func(x) for x in lst]) toc = time.perf_counter() print(toc - tic) # [1, 4, 9] # 15.0041916 --> output including 5 seconds sleep time
Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. It is process-wide by definition. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.
Use process_time_ns() to avoid the precision loss caused by the float type.
New in version 3.3.
So if you want it as nanoseconds , you can use time.process_time_ns() and if your code consist with time.sleep(secs), it won’t count. Ex:-
import time def func(x): time.sleep(5) return x * x lst = [1, 2, 3] tic = time.process_time() print([func(x) for x in lst]) toc = time.process_time() print(toc - tic) # [1, 4, 9] # 0.0 --> output excluding 5 seconds sleep time
Please note both time.perf_counter_ns() and time.process_time_ns() come up with Python 3.7 onward.
Как посчитать время программы? python
Я хотел бы спросить, почему в обоих случаях выводит 0, хотя программа работала довольно таки долго. И как это исправить?
с функцией я, вроде разобрался, что вызов функции нужно заключить между start_recur и stop_recur, а не саму функцию, но с циклом до сих пор думаю
у меня пара комментариев. 1)Вы вызываете свою функцию fib внутри print . . Получается, что вы просто меряете время ее создания, а не время ее работы. 2) Во всех подобных проблемах просто выводите значения всех переменных в консоль. Чаще всего поймете, что не так.
2 ответа 2
Сам решил, простите, что отвлёк. если кому нужно оставлю тут решение. С рекурсиями всё просто нужно заключать не рекурсию, а вызов функции
def fib(n): somecode start_recur = time.time() fib(n) end_recur = time.time()
start_recur = time.time() def fib(n): somecode end_recur = time.time() fib(n)
с циклом всё норм, он просто очень быстрый, смог засечь время только при очень больших цифрах
если что-то не так сказал поправьте, пожалуйста,
хотя как отметил комментатор выше, во втором случае мы измеряем время создание, а не время работы функции
Цикл реально будет работать очень быстро.
У вас там 31 итерация и в каждой только сложение и обмен значений. Это очень быстрые операции, там просто нечему долго работать.
На моей машине цикл выполняется за 0,000017 секунд.
Возможно, в вашем случае почему-то происходит округление до целых секунд.
Возможно, это связано с тем, что
Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls. (официальная документация)
(Краткий перевод: не все системы предоставляют время с точностью, большей чем 1 секунда).
Попробуйте на вашей системе многократно позапускать print(time.time()) и посмотрите — будет ли это вам выдавать дробные значения, или только значения, округлённые до целого.
Как измерить время выполнения функции в Python
Оптимизация и профилирование кода требуют от программистов умения измерять время выполнения отдельных функций. Это помогает выявить узкие места в коде и делает оптимизацию более целенаправленной. В этой статье мы рассмотрим различные подходы к измерению времени выполнения функции в Python.
Использование модуля time
Одним из наиболее прямых способов измерить время выполнения функции в Python является использование модуля time . Приведем пример его использования:
import time def my_func(): for _ in range(1000000): pass start_time = time.time() my_func() end_time = time.time() print(f"Функция выполнилась за секунд.")
Функция time.time() возвращает текущее время в секундах, прошедшее с начала эпохи (обычно это 00:00 1 января 1970 года).
Использование функции time.perf_counter
Функция time.perf_counter() представляет собой более точную альтернативу time.time() . Она измеряет время с максимально возможной точностью для вашей платформы.
import time def my_func(): for _ in range(1000000): pass start_time = time.perf_counter() my_func() end_time = time.perf_counter() print(f"Функция выполнилась за секунд.")
Использование функции time.process_time
Функция time.process_time() измеряет время процессора, вместо реального времени. Это может быть полезно для измерения времени выполнения функции, которое не зависит от других процессов в системе.
import time def my_func(): for _ in range(1000000): pass start_time = time.process_time() my_func() end_time = time.process_time() print(f"Функция выполнилась за секунд.")
Использование модуля timeit
Модуль timeit в Python предоставляет мощный и гибкий способ измерения времени выполнения небольших фрагментов кода. Он предназначен для избежания некоторых общих ловушек при измерении времени выполнения.
import timeit def my_func(): for _ in range(1000000): pass execution_time = timeit.timeit(my_func, number=1000) print(f"Функция выполнилась за секунд.")
Функция timeit.timeit() принимает два аргумента: функцию для выполнения и количество раз, которое нужно выполнить эту функцию.
Использование декораторов для измерения времени выполнения
Иногда может быть полезно создать декоратор для измерения времени выполнения функции. Это особенно полезно, если вам нужно измерить время выполнения многих функций.
import time def timer_decorator(func): def wrapper(*args, **kwargs): start_time = time.perf_counter() result = func(*args, **kwargs) end_time = time.perf_counter() print(f"Функция выполнилась за секунд.") return result return wrapper @timer_decorator def my_func(): for _ in range(1000000): pass my_func()
Заключение
Измерение времени выполнения функции в Python — важный навык для любого разработчика. Будь то простое использование модуля time , использование функций с большей точностью, таких как time.perf_counter() , или более сложные инструменты, такие как модуль timeit и декораторы, Python предлагает множество вариантов для решения этой задачи. Использование этих инструментов может помочь вам сделать ваш код более эффективным и быстрым.
Функция sorted() в Python: синтаксис, описание и примеры использования
Удаление элементов из списка Python: подробное объяснение с примерами
Функция divmod() в Python: деление с возвращением частного и остатка
Создание словарей Python из кортежей
Простые и эффективные способы замены элемента в списке Python
Преобразование списка в обратный список в Python: методы и приемы