我写了一个灵活的模拟程序。 Flexibe,因为用户应该能够通过python代码自定义计算。 对于自定义,他首先定义一些“常量”(在它们永远不会改变值的意义上的常量)。然后他可以使用常量和一些已知的预定义变量来定义python计算代码。此代码稍后在固定程序代码中处理。这是一个简化的例子:
# begin user input
WIDTH = 20.0 # user defined constants
COND = 10.0
calc_code = "COND*WIDTH*x" # x is a known changing Variable
# end user input
# begin hidden fixed program code
code = compile(
'''
def calc(x): # function that executes the user code
return ''' + calc_code
, '<string>', 'exec')
exec(code) # for python 2.x remove brackets
for x in range(10):
print(calc(x)) # for python 2.x remove brackets
# end hidden fixed program code
问题是用户代码经常执行并显着减慢计算速度。是否有可能以某种方式自动查找并预先计算代码中的常量项(COND * WIDTH)以获得显着的加速?