我正在使用python加载使用cdll.LoadLibrary()在c ++中生成的DLL(工作正常)。问题在于,每次调用该类时,我都需要在该类中重新加载DLL,否则它将产生不同的行为。
当我在类内重新加载dll时,代码将评估适应度函数约4192次(262次迭代),但是当我删除两行重新加载dll时,代码仅运行16次(一次迭代),并停止收敛之前。
这是我的代码:
import sys
import os
import pygmo as pg
from ctypes import *
pathname = os.path.dirname(sys.argv[0])
dllPath = os.path.join((os.path.abspath(pathname)), 'optmization_functions.dll')
mydll = cdll.LoadLibrary(dllPath)
mydll.rosen.restype = c_double
class RosenbrockDLL():
def __init__(self, n):
"""Pass dimensions to constructor."""
self.n = n
def fitness(self, x):
"""
The Rosenbrock function.
sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
"""
mydll = cdll.LoadLibrary(dllPath)
mydll.rosen.restype = c_double
x2 = (c_double * self.n)(*x)
r = mydll.rosen(c_int(self.n), x2)
return [r]
def get_bounds(self):
return ([-5]*self.n,[10]*self.n)
def pygmo_methods(func=RosenbrockDLL, N_vars=4, N_pop=16, N_gers=1000):
prob = pg.problem(func(n = N_vars))
algo = pg.algorithm(pg.de1220(gen = N_gers))
algo.set_verbosity(0)
archi = pg.archipelago(1, algo=algo, prob=prob, pop_size=N_pop)
archi.evolve(1)
archi.wait()
bestFevals = archi[0].get_population().problem.get_fevals()
print('\tFunction value:', *archi.get_champions_f())
print('\tDesign values:', *archi.get_champions_x())
print('\tFunction evaluations:', bestFevals)
print('\tNumber of generations:', bestFevals//N_pop)
if __name__ == "__main__":
N = 4
pygmo_methods(func=RosenbrockDLL, N_vars=N, N_pop=16, N_gers=1000)
现在,每次调用适应性代码时,代码都会重新加载dll,这会增加耗用的时间。我只想加载一次。