Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The library takes too long time than expected when using time.sleep function. #20

Open
Micro-sheep opened this issue Oct 5, 2021 · 0 comments

Comments

@Micro-sheep
Copy link

I run the code bellow on Linux ubuntu 5.10.0-8-amd64 with your library multitasking, normally, the time it cost should be about 10 seconds, however,it cost almost 30 seconds to finish the whole code.

import time
import multitasking
from datetime import datetime


@multitasking.task
def sleep(s: float, idx: int) -> None:
    print(f'Thread {idx} started at', datetime.today())
    time.sleep(s)


multitasking.set_max_threads(100)
st = time.time()
for i in range(10):
    sleep(10, i+1)
multitasking.wait_for_tasks()
et = time.time()
print('Cost:', et-st, 's')

Output

Thread 1 started at 2021-10-05 10:10:40.820264
Thread 2 started at 2021-10-05 10:10:40.820646
Thread 3 started at 2021-10-05 10:10:40.822117
Thread 4 started at 2021-10-05 10:10:40.823953
Thread 5 started at 2021-10-05 10:10:50.830119
Thread 6 started at 2021-10-05 10:10:50.830896
Thread 7 started at 2021-10-05 10:10:50.831372
Thread 8 started at 2021-10-05 10:10:50.833745
Thread 9 started at 2021-10-05 10:11:00.831055
Thread 10 started at 2021-10-05 10:11:00.841716
Cost: 30.023271560668945 s

But with other way like this, it just cost about 10 seconds.

import time
from typing import List
import multitasking
from datetime import datetime
from threading import Thread


def sleep(s: float, idx: int) -> None:
    print(f'Thread {idx} started at', datetime.today())
    time.sleep(s)


multitasking.set_max_threads(100)
st = time.time()
tasks: List[Thread] = []
for i in range(10):
    t = Thread(target=sleep, args=(10, i+1))
    tasks.append(t)
for t in tasks:
    t.start()
for t in tasks:
    t.join()
et = time.time()
print('Cost:', et-st, 's')

Output

Thread 1 started at 2021-10-05 10:21:38.460654
Thread 2 started at 2021-10-05 10:21:38.460975
Thread 3 started at 2021-10-05 10:21:38.461291
Thread 4 started at 2021-10-05 10:21:38.463486
Thread 5 started at 2021-10-05 10:21:38.463916
Thread 6 started at 2021-10-05 10:21:38.464316
Thread 7 started at 2021-10-05 10:21:38.465013
Thread 8 started at 2021-10-05 10:21:38.465399
Thread 9 started at 2021-10-05 10:21:38.465883
Thread 10 started at 2021-10-05 10:21:38.466408
Cost: 10.016554594039917 s

Could you please tell me the reason? This library is so cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant