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