Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "range" resource consumption

I wrote the following script

Basically, I'm just learning Python for Machine Learning and wanted to check how really computationally intensive tasks would perform. I observe that for 10**8 iterations, Python takes up a lot of RAM (around 3.8 GB) and also a lot of CPU time (just froze my system)

I want to know if there is any way to limit the time/memory consumption either through code or some global settings

Script -

initial_start = time.clock()
for i in range(9):
 start = time.clock()
 for j in range(10**i):
  pass
 stop = time.clock()
 print 'Looping exp(',i,') times takes', stop - start, 'seconds'
final_stop = time.clock()
print 'Overall program time is',final_stop - initial_start,'seconds'
like image 782
Sammy25 Avatar asked Oct 31 '25 16:10

Sammy25


1 Answers

In Python 2, range creates a list. Use xrange instead. For a more detailed explanation see Should you always favor xrange() over range()?

Note that a no-op for loop is a very poor benchmark that tells you pretty much nothing about Python.

Also note, as per gnibbler's comment, Python 3's range is works like Python 2's xrange.

like image 173
Steven Rumbalski Avatar answered Nov 02 '25 06:11

Steven Rumbalski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!