
ALT import timeit my_dict = {i: i for i in range(10000)} key = 9999 # A key that exists # Test direct dictionary lookup time1 = timeit.timeit(lambda: key in my_dict, number=1000000) # Test with dict.keys() time2 = timeit.timeit(lambda: key in my_dict.keys(), number=1000000) print(f"Direct lookup: {time1:.6f} sec") print(f"With .keys(): {time2:.6f} sec") # Direct lookup: 0.058519 sec # With .keys(): 0.091403 sec
![# Bad: Using threading for CPU-heavy tasks: import threading def expensive_task(): sum(i**2 for i in range(10**7)) threads = [threading.Thread(target=expensive_task) for _ in range(4)] for t in threads: t.start() for t in threads: t.join() # Here, Python's GIL ensures only one thread executes at a time for CPU tasks. So it's basically wasting context-switching overhead. # --- # Better: Use multiprocessing for CPU-bound tasks: from multiprocessing import Pool def expensive_task(_): return sum(i**2 for i in range(10**7)) with Pool(processes=4) as pool: pool.map(expensive_task, range(4)) # Uses multiple cores efficiently # Rule: Use threading for I/O-bound tasks, but use multiprocessing for CPU-bound tasks.](https://pbs.twimg.com/media/GmWmiuMWcAAYdnS.jpg?name=small&format=webp)
ALT # Bad: Using threading for CPU-heavy tasks: import threading def expensive_task(): sum(i**2 for i in range(10**7)) threads = [threading.Thread(target=expensive_task) for _ in range(4)] for t in threads: t.start() for t in threads: t.join() # Here, Python's GIL ensures only one thread executes at a time for CPU tasks. So it's basically wasting context-switching overhead. # --- # Better: Use multiprocessing for CPU-bound tasks: from multiprocessing import Pool def expensive_task(_): return sum(i**2 for i in range(10**7)) with Pool(processes=4) as pool: pool.map(expensive_task, range(4)) # Uses multiple cores efficiently # Rule: Use threading for I/O-bound tasks, but use multiprocessing for CPU-bound tasks.













