Reputation: 696
I would like to compare different solutions to the same problem using consumed memory like metric.
By example, what is the consumed memory from:
import itertools
def queens ():
for p in itertools.permutations (range (8) ):
yield [x for x in enumerate (p) ]
for q in queens ():
err = False
for a, b in ( (a, b) for a in q for b in q if a [0] < b [0] ):
if abs (a [0] - b [0] ) == abs (a [1] - b [1] ):
err = True
break
if not err: print (q)
And what is the consumed memory from:
SIZE=8
A=[0] * SIZE # Array solution
s=0 # Global variable to count 'solutions', you can delete it!
t=0 # Global variable to count recursion 'tests', you can delete it!
def test(queen, col):
global t
t+=1
for i in range(1,queen):
if(A[queen-i-1]==col): return 0 # Test vertical
if(A[queen-i-1]==col-i): return 0 # Test diagonal 1 (\)
if(A[queen-i-1]==col+i): return 0 # Test diagonal 2 (/)
return 1
def play(queen):
global s
for col in range(1,SIZE+1):
if(test(queen,col)): # If I can play the queen...
A[queen-1]=col # Add queen to the solution Array
if(queen==SIZE): # If the last queen was played, this is a solution
s+=1
print("Solution: {}, {}, {}".format(s,t,A))
else:
play(queen+1); # If not last queen, play the next one
A[queen-1]=0 # Clean the solution Array
play(1) # Start putting first queen
Upvotes: 2
Views: 2632
Reputation: 696
I found some interesting links:
How do I profile memory usage in Python? (stack overflow)
In summary, one solution is:
import tracemalloc
tracemalloc.start()
#
# code to test here
#
current, peak = tracemalloc.get_traced_memory()
print(f"Current memory usage is {current / 10**3}KB; Peak was {peak / 10**3}KB; Diff = {(peak - current) / 10**3}KB")
tracemalloc.stop()
Upvotes: 2