Created
August 2, 2012 10:05
-
-
Save MartinThoma/3236052 to your computer and use it in GitHub Desktop.
Test how fast multiplication and addition is.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# -*- coding: utf-8 -*- | |
""" | |
This script shows that addition and multiplication is similar | |
in terms of execution speed. | |
""" | |
import random, datetime | |
def add(n, minimum=-4000, maximum=4000): | |
x = 0 | |
random.seed(0) | |
start = datetime.datetime.now() | |
for i in xrange(n): | |
x = random.randint(minimum, maximum) + random.randint(minimum, maximum) | |
end = datetime.datetime.now() | |
delta = end - start | |
return delta.microseconds | |
def mul(n, minimum=-4000, maximum=4000): | |
x = 0 | |
random.seed(0) | |
start = datetime.datetime.now() | |
for i in xrange(n): | |
x = random.randint(minimum, maximum) * random.randint(minimum, maximum) | |
end = datetime.datetime.now() | |
delta = end - start | |
return delta.microseconds | |
def addF(n, minimum=-4000, maximum=4000, div=100.0): | |
x = 0 | |
random.seed(0) | |
start = datetime.datetime.now() | |
for i in xrange(n): | |
x = random.randint(minimum, maximum) / div + random.randint(minimum, maximum) / div | |
end = datetime.datetime.now() | |
delta = end - start | |
return delta.microseconds | |
def mulF(n, minimum=-4000, maximum=4000, div=100.0): | |
x = 0 | |
random.seed(0) | |
start = datetime.datetime.now() | |
for i in xrange(n): | |
x = (random.randint(minimum, maximum)/ div) * (random.randint(minimum, maximum)/div) | |
end = datetime.datetime.now() | |
delta = end - start | |
return delta.microseconds | |
if __name__ == "__main__": | |
N = 1000000 | |
print("Time for addition (int):\t%i" % add(N)) | |
print("Time for multiplication (int):\t%i" % mul(N)) | |
print("Time for addition (float):\t%i" % addF(N)) | |
print("Time for multiplication (f):\t%i" % mulF(N)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment