返回介绍

C++ version

发布于 2025-02-25 23:44:03 字数 1469 浏览 0 评论 0 收藏 0

Using C++ is almost the same as using C. Just add an extern C statement and use an appropriate C++ compiler.

%%file pdist_cpp.cpp
#include <cmath>

extern "C"

// Variable length arrays are OK for C99 but not legal in C++
// void pdist_cpp(int n, int p, double xs[n*p], double D[n*n]) {
void pdist_cpp(int n, int p, double *xs, double *D) {
    for (int i=0; i<n; i++) {
        for (int j=0; j<n; j++) {
            double s = 0.0;
            for (int k=0; k<p; k++) {
                double tmp = xs[i*p+k] - xs[j*p+k];
                s += tmp*tmp;
            }
            D[i*n+j] = sqrt(s);
        }
    }
}
Writing pdist_cpp.cpp
# Compile to a shared library
! g++ -O3 -bundle -undefined dynamic_lookup pdist_cpp.cpp -o pdist_cpp.so
# Linux:
# ! g++ -O3 -fPIC -shared pdist_cpp.cpp -o pdist_cpp.so
from ctypes import CDLL, c_int, c_void_p

def pdist_cpp(xs):

    # Use ctypes to load the library
    lib = CDLL('./pdist_cpp.so')

    # We need to give the argument adn return types explicitly
    lib.pdist_cpp.argtypes = [c_int, c_int, np.ctypeslib.ndpointer(dtype = np.float), np.ctypeslib.ndpointer(dtype = np.float)]
    lib.pdist_cpp.restype  = c_void_p

    n, p = xs.shape
    D = np.empty((n, n), np.float)

    lib.pdist_cpp(n, p, xs, D)
    return D
print pdist_cpp(A)
%timeit pdist_cpp(xs)
[[ 0.  5.]
 [ 5.  0.]]
100 loops, best of 3: 7.56 ms per loop

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文