""" John Rachlin DS 2000: Intro to Programming with Data Date: Wed Sep 21 20:09:56 2022 File: io_is_slow.py Description: How fast can we add the numbers 1-million """ #%% # A cell is a block of code we can run in isolation # Cells are not part of python. Spyder provides this feature # To start a new cell, use the special comment code: $%% # There are options in the toolbar to: # - Run current cell and stay in that cell # - Run current cell and advance to next cell # - variables declared in a previously executed cell # are remembered in subsequence cells. # Cells are merely a TEACHING aid for DEMONSTRATING elements # of python. Your code should STILL HAVE A MAIN()! name = "John" print("Hello", name) #%% minval = min(3,6,2,4,1,9) maxval = max(5,6,3,4,2,1) print(minval, maxval) #%% WHILE loops """ while loops let us repeat a block of code over and over WHILE some specified condition is true. If the condition becomes false, the while loop stops repeating. """ # Counting to 10 counter = 0 while counter < 10: counter = counter + 1 print(counter) print("Done") #%% # Counting to a million! counter = 0 while counter < 1000000: counter = counter + 1 print(counter) print("Done") #%% Timing our code import time current_time = time.time() print("seconds: ", current_time) # seconds since Jan 1, 1970 print("years : ", current_time / (3600 * 24 * 365.25)) #%% How fast can we count to a million? # Counting to a million! start = time.time() counter = 0 while counter < 1000000: counter = counter + 1 print(counter) print("Done") finish = time.time() elapsed = finish - start print("It took", elapsed, "seconds") #%% Counting WITHOUT printing is much faster! import time start = time.time() counter = 0 while counter < 1000000: counter = counter + 1 finish = time.time() elapsed_np = finish - start print("It took", elapsed_np, "seconds") pct_counting = elapsed_np / elapsed * 100.0 pct_printing = (elapsed - elapsed_np) / elapsed * 100.0 print("% time printing:", round(pct_printing,2)) print("% time counting:", round(pct_counting,2)) print("% Total :", round(pct_printing + pct_counting,2))