Advertisement
here2share

# global_vs_local.py

Feb 4th, 2024
998
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. # global_vs_local.py
  2.  
  3. from time import perf_counter
  4.  
  5. global_var = 10
  6. ttt = range(5_000_000)
  7.  
  8. for i in '.'*50:
  9.     start = perf_counter()
  10.     def local_func():
  11.         ans = 0
  12.         local_var = global_var
  13.         for i in ttt:
  14.             ans += global_var
  15.         return ans
  16.     local_func()
  17.     local_time = perf_counter()-start
  18.  
  19.     start = perf_counter()
  20.     def global_func():
  21.         ans = 0
  22.         for i in ttt:
  23.             ans += global_var
  24.         return ans
  25.     global_func()
  26.     global_time = perf_counter()-start
  27.  
  28.     print(f"")
  29.     print(f"local_time = {local_time:0f}")
  30.     print(f"global_time = {global_time:0f}")
  31.     a, b = 'local_func', 'global_func'
  32.     t = global_time-local_time
  33.     if local_time > global_time:
  34.         a, b = b, a
  35.         t = local_time-global_time
  36.     print(f"{a} is {t:0f} seconds faster then {b}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement