Apr-27-2024, 07:41 AM
hi
in the below code, after running, the usage of memory is shown as a negative number! why?
my output in Thonny:
in the below code, after running, the usage of memory is shown as a negative number! why?
#from:https://blog.faradars.org/reduce-memory-usage-and-make-your-python-code-faster-using-generators/ '''generators''' ''' problem to be solved: in a large list( for example 100,000,000) calculate the cube of even numbers. ''' import memory_profiler import time #ordianary method: def check_even_list(numbers): even = [] for num in numbers: if num % 2 == 0: even.append(num*num) return even #using generator def check_even_gene(numbers): for num in numbers: if num % 2 == 0: yield num * num if __name__ == '__main__': n=100_000_000 #n=100 m1 = memory_profiler.memory_usage() t1 = time.time() cubes = check_even_list(range(n)) #ordinary method with using list t2 = time.time() m2 = memory_profiler.memory_usage() # breakpoint set here in this line time_diff = t2 - t1 mem_diff = m2[0] - m1[0] print(f"It took {time_diff} Secs and {mem_diff} Mb to execute this method with using list.") m3 = memory_profiler.memory_usage() t3 = time.time() cubes = check_even_gene(range(n)) t4 = time.time() m4 = memory_profiler.memory_usage() time_diff = t4 - t3 mem_diff = m4[0] - m3[0] print(f"It took {time_diff} Secs and {mem_diff} Mb to execute this method with using generator.")
my output in Thonny:
Output:It took 27.66528820991516 Secs and 1913.3046875 Mb to execute this method with using list.
It took 1.9990813732147217 Secs and -1912.48828125 Mb to execute this method with using generator.
if I change n to 100, the consumed time is zero as below, why?Output:It took 0.0 Secs and 0.00390625 Mb to execute this method with using list.
It took 0.0 Secs and 0.0 Mb to execute this method with using generator.
thanks for any reply