Skip to content

Instantly share code, notes, and snippets.

@homm
Created June 9, 2012 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save homm/2901293 to your computer and use it in GitHub Desktop.
Save homm/2901293 to your computer and use it in GitHub Desktop.
from __future__ import print_function
import time
input = '10 20 100 + - 20 * DUP 10 20 + *';
t = time.time()
for x in xrange(0, 100000):
stack = []
for chunk in input.split(' '):
if chunk == '+':
stack.append(stack.pop() + stack.pop())
elif chunk == '-':
stack.append(stack.pop() - stack.pop())
elif chunk == '*':
stack.append(stack.pop() * stack.pop())
elif chunk == '=':
stack.append(stack.pop() == stack.pop())
elif chunk == 'DUP':
stack.append(stack[0])
elif chunk == 'DUMP':
print(stack)
else:
stack.append(int(chunk))
print('Python list: %f' % (time.time() - t))
print(stack)
from __future__ import print_function
import time
def forth_calc(input):
stack = []
for chunk in input.split(' '):
if chunk == '+':
stack.append(stack.pop() + stack.pop())
elif chunk == '-':
stack.append(stack.pop() - stack.pop())
elif chunk == '*':
stack.append(stack.pop() * stack.pop())
elif chunk == '=':
stack.append(stack.pop() == stack.pop())
elif chunk == 'DUP':
stack.append(stack[0])
elif chunk == 'DUMP':
print(stack)
else:
stack.append(int(chunk))
return stack
input = '10 20 100 + - 20 * DUP 10 20 + *'
t = time.time()
for x in xrange(0, 100000):
forth_calc(input)
print('Python list: %f' % (time.time() - t))
print(forth_calc(input))
from __future__ import print_function
import time
def forth_calc(input):
stack = []
append = stack.append
pop = stack.pop
for chunk in input.split(' '):
if chunk == '+':
append(pop() + pop())
elif chunk == '-':
append(pop() - pop())
elif chunk == '*':
append(pop() * pop())
elif chunk == '=':
append(pop() == pop())
elif chunk == 'DUP':
append(stack[-1])
elif chunk == 'DUMP':
print(stack)
else:
append(int(chunk))
return stack
input = '10 20 100 + - 20 * DUP 10 20 + *'
t = time.time()
for x in xrange(0, 100000):
forth_calc(input)
print('Python list: %f' % (time.time() - t))
print(forth_calc(input))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment