Comparing the parallel and sequential implementations to measure performance gains

comparing the parallel and sequential implementations to measure performance gains.

python

import asyncio
import multiprocessing
from typing import List

async def perform_async_task(index: int) → None:
“”“Perform an asynchronous task.”“”
print(f"Start async task {index}“)
await asyncio.sleep(1)
print(f"End async task {index}”)

def run_async_tasks(index_range: List[int]) → None:
“”“Run a set of asynchronous tasks.”“”
loop = asyncio.get_event_loop()
tasks = [perform_async_task(i) for i in index_range]
loop.run_until_complete(asyncio.gather(*tasks))

def grant_permissions(role: str, permissions: List[str]) → None:
“”“Grant permissions to a role.”“”
query = f’GRANT {“, “.join(permissions)} ON api_key TO {role}’
try:
# Simulate executing the SQL query
print(f"Executing query: {query}”)
except Exception as e:
print(f"Error executing query: {query}. Error: {e}”)

def main() → None:
try:
roles_permissions = {
‘admin’: [‘ALL’],
‘user’: [‘SELECT’, ‘INSERT’]
}

    num_processes = multiprocessing.cpu_count()
    tasks_per_process = 2
    total_tasks = num_processes * tasks_per_process

    processes = []
    for i in range(num_processes):
        start_index = i * tasks_per_process
        end_index = start_index + tasks_per_process
        process = multiprocessing.Process(target=run_async_tasks, args=(range(start_index, end_index),))
        processes.append(process)

    for process in processes:
        process.start()

    for process in processes:
        process.join()

    print("All processes completed.")

    # Grant permissions based on roles
    for role, permissions in roles_permissions.items():
        grant_permissions(role, permissions)
        
except Exception as e:
    print(f"An unexpected error occurred: {e}")

if name == “main”:
main()

Enhancements made in this version:

Descriptive Function Names:
    Renamed functions for better clarity and adherence to naming conventions.

Docstrings:
    Added docstrings to functions for improved documentation.

Structured Comments:
    Comments are structured and provide more context.

Improved Exception Handling:
    Catching more generic exceptions for better resilience.

Function Documentation:
    Added comments and documentation for each function to explain its purpose.

Function Parameters:
    Ensured consistent usage of function parameters.

Use of perform_async_task Function:
    Renamed the async_task function to perform_async_task for clarity.

Explicit Variable Naming:
    Used more descriptive variable names.

This version aims to provide a refined, robust, and smooth codebase with additional clarity and documentation.