tqdm but with parallel execution. Will essentially return res = [ function(arg) # default function(*arg) # if star_args is True function(**arg) # if kw_args is True for arg in args] Note: the first elements of args will
(function, args, workers=0, star_args=False, kw_args=False, front_num=1, Pool=ThreadPool, **tqdm_kw)
| 10 | |
| 11 | |
| 12 | def parallel_threads(function, args, workers=0, star_args=False, kw_args=False, front_num=1, Pool=ThreadPool, **tqdm_kw): |
| 13 | """ tqdm but with parallel execution. |
| 14 | |
| 15 | Will essentially return |
| 16 | res = [ function(arg) # default |
| 17 | function(*arg) # if star_args is True |
| 18 | function(**arg) # if kw_args is True |
| 19 | for arg in args] |
| 20 | |
| 21 | Note: |
| 22 | the <front_num> first elements of args will not be parallelized. |
| 23 | This can be useful for debugging. |
| 24 | """ |
| 25 | while workers <= 0: |
| 26 | workers += cpu_count() |
| 27 | if workers == 1: |
| 28 | front_num = float('inf') |
| 29 | |
| 30 | # convert into an iterable |
| 31 | try: |
| 32 | n_args_parallel = len(args) - front_num |
| 33 | except TypeError: |
| 34 | n_args_parallel = None |
| 35 | args = iter(args) |
| 36 | |
| 37 | # sequential execution first |
| 38 | front = [] |
| 39 | while len(front) < front_num: |
| 40 | try: |
| 41 | a = next(args) |
| 42 | except StopIteration: |
| 43 | return front # end of the iterable |
| 44 | front.append(function(*a) if star_args else function(**a) if kw_args else function(a)) |
| 45 | |
| 46 | # then parallel execution |
| 47 | out = [] |
| 48 | with Pool(workers) as pool: |
| 49 | # Pass the elements of args into function |
| 50 | if star_args: |
| 51 | futures = pool.imap(starcall, [(function, a) for a in args]) |
| 52 | elif kw_args: |
| 53 | futures = pool.imap(starstarcall, [(function, a) for a in args]) |
| 54 | else: |
| 55 | futures = pool.imap(function, args) |
| 56 | # Print out the progress as tasks complete |
| 57 | for f in tqdm(futures, total=n_args_parallel, **tqdm_kw): |
| 58 | out.append(f) |
| 59 | return front + out |
| 60 | |
| 61 | |
| 62 | def parallel_processes(*args, **kwargs): |
no outgoing calls
no test coverage detected