Модуль time в python

Использование time.sleep() в threading

Python  является хорошим примером использования . Модуль логирования logging является потоко-безопасным, поэтому в данном примере он будет полезнее, чем операторы . В основе следующего кода лежит данный пример:

import logging
import threading
import time

def worker(arg):
while not arg:
logging.debug(«рабочий поток вносится»)
time.sleep(1)

def main():
logging.basicConfig(
level=logging.DEBUG,
format=»%(relativeCreated)6d %(threadName)s %(message)s»
)
info = {«stop»: False}
thread = threading.Thread(target=worker, args=(info,))
thread_two = threading.Thread(target=worker, args=(info,))
thread.start()
thread_two.start()

while True:
try:
logging.debug(«Добавление из главного потока»)
time.sleep(0.75)
except KeyboardInterrupt:
info = True
logging.debug(‘Остановка’)
break
thread.join()
thread_two.join()

if __name__ == «__main__»:
main()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

import logging

import threading

import time

def worker(arg)

whilenotarg»stop»

logging.debug(«рабочий поток вносится»)

time.sleep(1)

def main()

logging.basicConfig(

level=logging.DEBUG,

format=»%(relativeCreated)6d %(threadName)s %(message)s»

)

info={«stop»False}

thread=threading.Thread(target=worker,args=(info,))

thread_two=threading.Thread(target=worker,args=(info,))

thread.start()

thread_two.start()

whileTrue

try

logging.debug(«Добавление из главного потока»)

time.sleep(0.75)

except KeyboardInterrupt

info»stop»=True

logging.debug(‘Остановка’)

break

thread.join()

thread_two.join()

if__name__==»__main__»

main()

Здесь для создания двух потоков используется модуль Python . Также создается объект входа, что будет вводить  в . Затем начинаются оба потока и инициируется цикл для каждого входа из главного потока. Для фиксирования пользователя используется  при нажатии .

Попробуйте запустить вышеуказанный код в терминале. Ваш вывод должен походить на следующий:

2 Thread-1 рабочий поток вносится
4 Thread-2 рабочий поток вносится
4 MainThread Добавление из главного потока
755 MainThread Добавление из главного потока
1004 Thread-1 рабочий поток вносится
1006 Thread-2 рабочий поток вносится
1506 MainThread Добавление из главного потока
2005 Thread-1 рабочий поток вносится
2007 Thread-2 рабочий поток вносится
2257 MainThread Добавление из главного потока
3007 Thread-1 рабочий поток вносится
3008 MainThread Добавление из главного потока

1
2
3
4
5
6
7
8
9
10
11
12

2Thread-1рабочийпотоквносится

4Thread-2рабочийпотоквносится

4MainThreadДобавлениеизглавногопотока

755MainThreadДобавлениеизглавногопотока

1004Thread-1рабочийпотоквносится

1006Thread-2рабочийпотоквносится

1506MainThreadДобавлениеизглавногопотока

2005Thread-1рабочийпотоквносится

2007Thread-2рабочийпотоквносится

2257MainThreadДобавлениеизглавногопотока

3007Thread-1рабочийпотоквносится

3008MainThreadДобавлениеизглавногопотока

Когда каждый поток работает, а затем уходит в сон, выходные данные выводятся в консоль. Теперь, разобрав пример, вы сможете использовать данные концепции в своем собственном коде.

Choosing the clock from a list of constraints

The PEP as proposed offers a few new clocks, but their guarantees
are deliberately loose in order to offer useful clocks on different
platforms. This inherently embeds policy in the calls, and the
caller must thus choose a policy.

The «choose a clock» approach suggests an additional API to let
callers implement their own policy if necessary
by making most platform clocks available and letting the caller pick amongst them.
The PEP’s suggested clocks are still expected to be available for the common
simple use cases.

To do this two facilities are needed:
an enumeration of clocks, and metadata on the clocks to enable the user to
evaluate their suitability.

The primary interface is a function make simple choices easy:
the caller can use time.get_clock(*flags) with some combination of flags.
This includes at least:

  • time.MONOTONIC: clock cannot go backward
  • time.STEADY: clock rate is steady
  • time.ADJUSTED: clock may be adjusted, for example by NTP
  • time.HIGHRES: clock with the highest resolution

It returns a clock object with a .now() method returning the current time.
The clock object is annotated with metadata describing the clock feature set;
its .flags field will contain at least all the requested flags.

time.get_clock() returns None if no matching clock is found and so calls can
be chained using the or operator. Example of a simple policy decision:

T = get_clock(MONOTONIC) or get_clock(STEADY) or get_clock()
t = T.now()

The available clocks always at least include a wrapper for time.time(),
so a final call with no flags can always be used to obtain a working clock.

Examples of flags of system clocks:

  • QueryPerformanceCounter: MONOTONIC | HIGHRES
  • GetTickCount: MONOTONIC | STEADY
  • CLOCK_MONOTONIC: MONOTONIC | STEADY (or only MONOTONIC on Linux)
  • CLOCK_MONOTONIC_RAW: MONOTONIC | STEADY
  • gettimeofday(): (no flag)

The clock objects contain other metadata including the clock flags
with additional feature flags above those listed above, the name
of the underlying OS facility, and clock precisions.

time.get_clock() still chooses a single clock; an enumeration
facility is also required.
The most obvious method is to offer time.get_clocks() with the
same signature as time.get_clock(), but returning a sequence
of all clocks matching the requested flags.
Requesting no flags would thus enumerate all available clocks,
allowing the caller to make an arbitrary choice amongst them based
on their metadata.

Time Module

This module provides functions that help manipulate time and use them in your program. There are other «cousin» modules that work more precisely with date and the calendar within your system, but this module is more focused on just manipulating time — working with hours going all the way down to milliseconds.

Some of the terms you will generally hear when working with time in the computer science world is epoch.

But first, make sure you import the time module. To do so simply type:

epoch

This is the precise point when time really started. This doesn’t mean the birth of our solar system or when man actually started measuring time, but it is actually relatively closer to now. For the UNIX system, the epoch is January 1, 1970, 00:00:00 (UTC) (It was a Thursday in case you were wondering…) To find out the epoch on your system you can type:

This will tell you the year (tm_year), month (tm_mon), day (tm_mday), hour (tm_hour), minute (tm_min) and the second (tm_sec). Along with week of the day (tm_wday) — this is 3 since Monday is marked as the beginning of the week and is counted as 0. Then it is followed by the day of the year (tm_yday) aka julian day. And finally, the daylight saving flag (tm_isdst) — DST stands for daylight saving time. This field has values either 0, -1 or 1. 0, if the daylight savings is not in effect. 1, if the daylight savings is in effect and finally -1, if the information is not available. Why not available you ask? Because DST rules are determined by local law and can change.

Most computers store the time and date as a difference of seconds from the date January 1, 1970, 00:00:00 (UTC) and the time that is to be stored. So, if you go ahead and type:

This will tell you the seconds that have passed since January 1, 1970, 00:00:00 (UTC). This difference is what we call timestamp or UNIX epoch time, and it is in the form of a floating point number. Well… to be honest, the difference is not in terms of seconds but something called ticks. In most UNIX systems, the clock «ticks» 50 to 100 times in a second. So, the UNIX epoch time is actually the number of ticks that have occurred since Jan 1, 1970, 00:00:00 UTC.

So, now that you have an idea about what the time module does. Let’s have a look at the function.

Using Timer

The Timer is another method available with Threading, and it helps to get the same functionality as sleep. The working of the Timer is shown in the example below:

Example:

A Timer takes in input as the delay time in seconds, along with a task that needs to be started. To make a timer working, you need to call the start() method. In the code, the Timer is given 5 seconds, and the function display that has to be called when 5 seconds are done. The timer will start working when the Timer.start() method is called.

from threading import Timer

print('Code Execution Started')

def display():
    print('Welcome to Guru99 Tutorials')

t = Timer(5, display)  
t.start()

Output:

Code Execution Started
Welcome to Guru99 Tutorials

Summary:

  • Python sleep() function will pause or delay the execution of code for the number of seconds given as input to sleep(). The sleep() function is part of the time module.
  • You can make use of sleep() function when you want to temporarily halt the execution of your code. For example, in case you are waiting for another process to complete, or a file upload, etc.
  • There are many ways to add delay to code besides sleep, and they are using asyncio.sleep , Event().wait and Timer.
  • Similar to sleep() method, there is asyncio.sleep() method with python version 3.4 and higher. To make use of the asyncio sleep method, you need to add async and await to the function
  • The Event().wait method comes from the threading module. Event.wait() method will halt the execution of any process for the number of seconds it takes as an argument.
  • The Timer is another method available with Threading, and it helps to get the same functionality as sleep
Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector