1# -*- coding: utf-8 -*- 2import random 3import os 4import time 5import datetime as dt 6 7nfns = 4 # Functions per class 8nargs = 4 # Arguments per function 9 10 11def generate_dummy_code_pybind11(nclasses=10): 12 decl = "" 13 bindings = "" 14 15 for cl in range(nclasses): 16 decl += "class cl%03i;\n" % cl 17 decl += "\n" 18 19 for cl in range(nclasses): 20 decl += "class cl%03i {\n" % cl 21 decl += "public:\n" 22 bindings += ' py::class_<cl%03i>(m, "cl%03i")\n' % (cl, cl) 23 for fn in range(nfns): 24 ret = random.randint(0, nclasses - 1) 25 params = [random.randint(0, nclasses - 1) for i in range(nargs)] 26 decl += " cl%03i *fn_%03i(" % (ret, fn) 27 decl += ", ".join("cl%03i *" % p for p in params) 28 decl += ");\n" 29 bindings += ' .def("fn_%03i", &cl%03i::fn_%03i)\n' % (fn, cl, fn) 30 decl += "};\n\n" 31 bindings += " ;\n" 32 33 result = "#include <pybind11/pybind11.h>\n\n" 34 result += "namespace py = pybind11;\n\n" 35 result += decl + "\n" 36 result += "PYBIND11_MODULE(example, m) {\n" 37 result += bindings 38 result += "}" 39 return result 40 41 42def generate_dummy_code_boost(nclasses=10): 43 decl = "" 44 bindings = "" 45 46 for cl in range(nclasses): 47 decl += "class cl%03i;\n" % cl 48 decl += "\n" 49 50 for cl in range(nclasses): 51 decl += "class cl%03i {\n" % cl 52 decl += "public:\n" 53 bindings += ' py::class_<cl%03i>("cl%03i")\n' % (cl, cl) 54 for fn in range(nfns): 55 ret = random.randint(0, nclasses - 1) 56 params = [random.randint(0, nclasses - 1) for i in range(nargs)] 57 decl += " cl%03i *fn_%03i(" % (ret, fn) 58 decl += ", ".join("cl%03i *" % p for p in params) 59 decl += ");\n" 60 bindings += ( 61 ' .def("fn_%03i", &cl%03i::fn_%03i, py::return_value_policy<py::manage_new_object>())\n' 62 % (fn, cl, fn) 63 ) 64 decl += "};\n\n" 65 bindings += " ;\n" 66 67 result = "#include <boost/python.hpp>\n\n" 68 result += "namespace py = boost::python;\n\n" 69 result += decl + "\n" 70 result += "BOOST_PYTHON_MODULE(example) {\n" 71 result += bindings 72 result += "}" 73 return result 74 75 76for codegen in [generate_dummy_code_pybind11, generate_dummy_code_boost]: 77 print("{") 78 for i in range(0, 10): 79 nclasses = 2 ** i 80 with open("test.cpp", "w") as f: 81 f.write(codegen(nclasses)) 82 n1 = dt.datetime.now() 83 os.system( 84 "g++ -Os -shared -rdynamic -undefined dynamic_lookup " 85 "-fvisibility=hidden -std=c++14 test.cpp -I include " 86 "-I /System/Library/Frameworks/Python.framework/Headers -o test.so" 87 ) 88 n2 = dt.datetime.now() 89 elapsed = (n2 - n1).total_seconds() 90 size = os.stat("test.so").st_size 91 print(" {%i, %f, %i}," % (nclasses * nfns, elapsed, size)) 92 print("}") 93