Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it much slower to print an answer to a calculation when compared to just computing it?

Tags:

python

I'm computing the answer for some very big division questions and wonder why b=a/c (where a and c and both positive whole numbers) is so must faster to figure out than when you type the questions and ask that the answer be printed: b=a/c is way faster than b=a/c followed by print b.

Very slow:

from datetime import datetime - startTime = datetime.now()
a=2**1000000-3
b=a/13
print b
print(datetime.now()-startTime) 

but without the print b it is very fast. I later typed in c=a%13 to see if anything was actually happening (I'm still pretty new to programming) and it is very fast when I type in print c (without the print b code).

like image 918
user2898543 Avatar asked Jan 24 '26 18:01

user2898543


2 Answers

As far as I understand, IO operations are slow and printing to the screen is like writing to a file and it is going to block the thread for some time.

As someone pointed out, conversion from number to string could be taking time too. Whenever I have to measure time of something. I measure the time of the calculation and print any kind of result after measuring time.

To make the program even faster, but memory hungry, you could save every result in a list and then compile one big string and print only once.

Repetitive call to print take more time than one big call to print.

from datetime import datetime

startTime = datetime.now()

a=2**1000000-3
b=a/13

elapsedTime = datetime.now() - startTime

print "Elapsed time %s\n Number: %s" % (elapsedTime, b)
like image 167
Loïc Faure-Lacroix Avatar answered Jan 27 '26 09:01

Loïc Faure-Lacroix


You're trying to output pretty big number (about 10^300000) – it takes time to convert it to decimal format from binary (I guess need to do about 300000 divisions for this, internally numbers are stored in binary format). If you really need to output whole number in decimal format – I don't think you can speed it up a lot. But you can quickly print number in hex or binary format:

hex(b)
bin(b)

You can use Decimal type to store numbers in decimal format internally but calculations with this type could be much slower.

like image 41
alexius Avatar answered Jan 27 '26 09:01

alexius



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!