Timer cyclic task:
- Knowledge base
- Timer(interval, function, args=None, kwargs=None)
- interval === "time interval in s
- function === "custom function performed
- Use threading Timer class
- start () method is commonly started
- cancel () method to cancel execution of
- Normal Single timing of execution
Threading from Import the Timer Import Time # ordinary single-shot timer DEF handle (): Print ( "normal shot timer function is executed" ); T1 = the Timer (interval The. 1 =, = function handle); t1.start ();
Performing a timing loop
Threading the Timer Import from Import Time # Cycle Timer DEF loop_handle (): Print ( "timer function is executed cycle timer"); Global T2; T2 = the Timer (interval The. 1 =, = loop_handle function); t2.start () ; T2 = the Timer (interval the. 1 =, = loop_handle function); t2.start (); the time.sleep (. 5); the main thread stops # 5S; t2.cancel (); # T2 in the primary main execution thread blocks 5s t2 5s
Thread pool
basic concepts
- When the program starts on a number of threads created and saved to memory. When the thread is started and executed, it does not destroyed, but wait for the next re-use.
i: saving time destroy the process of creating the process, greatly reduce the overhead of process
- achieve
- Preemptive: thread pool thread execution order is not fixed. The manner of using ThreadPoolExecutor submit () method implementation.
- Specific function to perform that thread is random, and may also be inconsistent execution
- Run the function thread of execution appeared a crash, does not affect the whole other thread pool thread
- Use with syntax streamline operations
- Non-preemptive: thread will execute the order calls. This way of using ThreadPoolExecutor map () method to achieve
- Each thread processing functions are the same, one thread executes a function of the collapse, the overall collapse
The basic code
concurrent.futures from Import the ThreadPoolExecutor introduced thread pool # Import Time DEF printName (name): Print ( "name" , name); the time.sleep ( 2 ); nameList = [ 'Tom', 'jirl', 'Steam' ]; # preemptive thread pool start2 = the time.time (); with the ThreadPoolExecutor ( . 3 ) aS Executor: for I in nameList: # inconsistent because each execution of the function, the parameters to be passed separately executor.submit (printName, I); end2 = the time.time (); Print ( "Speed 2:", STR (end2- start2)); # non-preemptive thread pool
The number of threads formula:
Formula
Experience
(1) initialize certain number of threads.
(2) increment or decrement the number of threads, performance test run in multiple experiments.
(3) determine the number of threads the most worry.