python - What is the best way to calculate percentage of an iterating operation? -
i've written function saves numbers between 2 digit groups text file, step option save space , time, , couldn't figure out how show percentage value, tried this.
for length in range(int(limit_min), int(limit_max) + 1): percent_quotient = 0 j=0 while j <= (int(length * "9")): while len(str(j)) < length: j = "0" + str(j) percent_quotient+=1 j = int(j) + int(step) # increasing dummy variable length in range(int(limit_min), int(limit_max) + 1): counter=1 = 0 while <= (int(length * "9")): while len(str(i)) < length: = "0" + str(i) # print "writing %s file. progress: %.2f percent." % (str(i),(float(counter)/percent_quotient)*100) a.write(str(i) + "\n") # gets written = int(i) + int(step) # increasing counter+=1 if length != int(limit_max): print "length %i done. moving on length of %i." % (length, length + 1) else: print "length %i done." % (length) a.close() # closing file stream print "all done. closed file stream. new file size: %.2f megabytes." % (os.path.getsize(path) / float((1024 ** 2))) print "returning main..."
what tried here make program iteration many times it, instead of writing file, made percent_quotient variable count how many times iteration going repeated. (i called j
dummy variable since it's there break loop; i'm sorry if there expression this.) second part actual work , put counter variable, , divide percent_quotient
, multiply 100 percentage.
the problem is, when tried make dictionary length of 1 length of 8, took minute count everything. imagine take longer if wanted make bigger dictionary.
my question is, there better/faster way of doing this?
i can't work out doing. looks it's doing this:
a = file('d:/whatever.txt', 'wb') limit_min = 1 limit_max = 5 step = 2 percent_quotient = (10 ** (limit_max - limit_min)) / step in range(limit_min, 10**limit_max, step): output = str(i).zfill(limit_max) + '\r\n' a.write(output) if % 100 < 2: print "writing %s file. progress: %.2f percent." % (str(i),(float(i)/percent_quotient)*100) a.close()
if that's right, suggest:
- do less code looping , more math
- use
string.zfill()
instead ofwhile len(str(num)) < length: "0" + str(num)
- don't overwhelm console output every single number, print status update every hundred numbers, or every thousand numbers, or so.
- do less
str(int(str(int(str(int(str(int(...
- avoid
"" + blah
inside tight loops, if possible, causes strings rebuilt every time , it's particularly slow.
Comments
Post a Comment