I've heard that C++ is much faster than Python and I test that using pybind11.
I created two analogous classes, one in C++ (Foo
) and one in Python (Bar
). I then use pybind11 to use C++ class in Python.
The main idea of the class is that it should contain a custom class and calculate it for all integer numbers from 0 to x. I set here x to one million to see an impact in runtime.
main.cpp
#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <pybind11/operators.h>
#include <pybind11/stl.h>
using namespace std;
class Foo {
private:
function<double(int)> func;
double result[1000000];
public:
Foo(function<double(int)> f): func(f) {}
void calculate() {
for (int t=0; t<1000000; t++) {
result[t] = func(t);
}
}
};
PYBIND11_MODULE(cmake_example, m) {
pybind11::class_<Foo>(m, "Foo")
.def(pybind11::init<function<double(int)>>())
.def("calculate", &Foo::calculate);
m.attr("__version__") = "0.0.1";
}
mytest.py
import time
import cmake_example
class Bar:
def __init__(self, func):
self.func = func
self.result = [None for _ in range(1_000_000)]
def calculate(self):
for t in range(1_000_000):
self.result[t] = self.func(t)
def myfunction(t):
return t * t
if __name__ == "__main__":
start = time.time()
foo = cmake_example.Foo(myfunction)
foo.calculate()
print("cpp:", time.time() - start)
start = time.time()
bar = Bar(myfunction)
bar.calculate()
print("pyt:", time.time() - start)
and the result is:
cpp: 0.4998281002044678
pyt: 0.39750099182128906
I'm wondering - would other data types solve the issue? Why is C++ slower in that case than Python?
I expected that the C++ code will be faster.