Python Forum
negative memory usage - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: negative memory usage (/thread-42041.html)



negative memory usage - akbarza - Apr-27-2024

hi
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


RE: negative memory usage - Gribouillis - Apr-27-2024

(Apr-27-2024, 07:41 AM)akbarza Wrote: the usage of memory is shown as a negative number! why?
I think it is negative because the code deletes the previously calculated list cubes. You could correct this by running
del cubes
m3 = ...
Another major problem with your code is that the call to check_even_gene() creates a generator but it does not actually calculate the data num * num, so it basically does nothing.

Also note that num * num is not the cube of the number num.