Skip to content

Instantly share code, notes, and snippets.

@MartinThoma
Created August 2, 2012 10:05
Show Gist options
  • Save MartinThoma/3236052 to your computer and use it in GitHub Desktop.
Save MartinThoma/3236052 to your computer and use it in GitHub Desktop.
Test how fast multiplication and addition is.
#!/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