Executes a given function `fn` in parallel, using multiple threads, on a list of argument tuples. The function limits the number of concurrent executions to `max_workers` and processes tasks in chunks, pausing between each chunk to avoid hitting rate limits or quotas. Args: - f
(
fn: Callable,
list_of_kwargs: List[dict],
max_workers: Optional[int] = None,
jitter: float = 0.0,
)
| 19 | |
| 20 | |
| 21 | def parallel_exec( |
| 22 | fn: Callable, |
| 23 | list_of_kwargs: List[dict], |
| 24 | max_workers: Optional[int] = None, |
| 25 | jitter: float = 0.0, |
| 26 | ) -> list: |
| 27 | """ |
| 28 | Executes a given function `fn` in parallel, using multiple threads, on a list of argument tuples. |
| 29 | The function limits the number of concurrent executions to `max_workers` and processes tasks in chunks, |
| 30 | pausing between each chunk to avoid hitting rate limits or quotas. |
| 31 | |
| 32 | Args: |
| 33 | - fn (Callable): The function to execute in parallel. |
| 34 | - list_of_kwargs (list): A list of dicts, where each dict contains arguments for a single call to `fn`. |
| 35 | - max_workers (int, optional): The maximum number of threads that can be used to execute the tasks |
| 36 | concurrently. |
| 37 | - jitter (float, optional): Wait for jitter * random.random() before submitting the next job. |
| 38 | |
| 39 | Returns: |
| 40 | - A list containing the results of the function calls. The order of the results corresponds to the order |
| 41 | the tasks were completed, which may not necessarily be the same as the order of `list_of_kwargs`. |
| 42 | |
| 43 | """ |
| 44 | results = [] |
| 45 | with ThreadPoolExecutor(max_workers=max_workers) as executor: |
| 46 | # Get the tasks for the current chunk |
| 47 | futures = [] |
| 48 | for kwargs in list_of_kwargs: |
| 49 | futures.append(executor.submit(fn, **kwargs)) |
| 50 | if jitter > 0.0: |
| 51 | time.sleep(jitter * random.random()) |
| 52 | for future in as_completed(futures): |
| 53 | results.append(future.result()) |
| 54 | return results |
| 55 | |
| 56 | |
| 57 | # for debug |