我的代码在很大程度上依赖于计算3D空间中两点之间的距离.为了避免昂贵的平方根,我使用整个平方距离.但它仍然占用了计算时间的很大一部分,我想用更快的东西替换我的简单函数.我现在有:
double distance_squared(double *a, double *b)
{
double dx = a[0] - b[0];
double dy = a[1] - b[1];
double dz = a[2] - b[2];
return dx*dx + dy*dy + dz*dz;
}
Run Code Online (Sandbox Code Playgroud)
我也尝试使用宏来避免函数调用,但它没有多大帮助.
#define DISTANCE_SQUARED(a, b) ((a)[0]-(b)[0])*((a)[0]-(b)[0]) + ((a)[1]-(b)[1])*((a)[1]-(b)[1]) + ((a)[2]-(b)[2])*((a)[2]-(b)[2])
Run Code Online (Sandbox Code Playgroud)
我想过使用SIMD指令但是找不到一个好的例子或完整的指令列表(理想情况下是一些乘法+加两个向量).
GPU不是一个选项,因为每个函数调用只知道一组点.
计算距离平方的最快方法是什么?
更新后的原始问题:
我需要计算一个中位数,并希望使用O(N)quickselect算法.然而事实证明,当数组不再是平面数组的双精度数,而是结构数组(其中一个元素是用于中值计算的元素)时,运行时间不再与O(N)成比例.
以下平面阵列版本具有近似线性运行时:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SWAP(a,b) temp=(a);(a)=(b);(b)=temp;
double quickselect(unsigned long k, unsigned long n, double *arr)
{
unsigned long i, ir, j, l, mid;
double a, temp;
l=1;
ir=n-1;
for (;;) {
if (ir <= l+1) {
if (ir == l+1 && arr[ir] < arr[l]) {
SWAP(arr[l],arr[ir])
}
return arr[k];
} else {
mid=(l+ir) >> 1;
SWAP(arr[mid],arr[l+1])
if (arr[l] > arr[ir]) {
SWAP(arr[l],arr[ir])
}
if (arr[l+1] > arr[ir]) {
SWAP(arr[l+1],arr[ir])
}
if (arr[l] > …Run Code Online (Sandbox Code Playgroud) 我试图将一个小型数据分析程序从64位UNIX移植到32位Windows XP系统(不要问:)).但是现在我遇到了2GB文件大小限制的问题(在这个平台上长时间不是64位).
我搜索了这个网站和其他人可能的解决方案,但找不到任何可以直接翻译我的问题.问题在于使用fseek和ftell.
有没有人知道对以下两个函数的修改,使它们可以在32位Windows XP上运行大于2GB的文件(实际上是100GB).
至关重要的是,nsamples的返回类型是64位整数(可能是int64_t).
long nsamples(char* filename)
{
FILE *fp;
long n;
/* Open file */
fp = fopen(filename, "rb");
/* Find end of file */
fseek(fp, 0L, SEEK_END);
/* Get number of samples */
n = ftell(fp) / sizeof(short);
/* Close file */
fclose(fp);
/* Return number of samples in file */
return n;
}
Run Code Online (Sandbox Code Playgroud)
和
void readdata(char* filename, short* data, long start, int n)
{
FILE *fp;
/* Open file */
fp = fopen(filename, "rb");
/* …Run Code Online (Sandbox Code Playgroud) 我有一些 C++ 方法std::set<std::string>作为参数或返回值。我想将其映射到 Python frozenset(或常规set),但似乎没有一种直接的方法可以做到这一点。有谁知道如何完成这项任务。
我最近将一个库,我最初使用Boost Python包装,用C++编写,用SWIG包装来支持更多语言.我从C++切换到C,因为该库只包含一组函数,我也希望该库可以从C调用(无需用C++编译器编译整个程序).然而,有一件事不容易移植,一小部分功能需要能够报告错误.在C++/Boost Python中,非常优雅地完成了throw异常翻译.
如果有一部分函数报告错误,最优雅的方式(在C语言和包装语言方面)会是什么?
c ×4
optimization ×2
python ×2
boost-python ×1
c++ ×1
c99 ×1
large-files ×1
porting ×1
simd ×1
swig ×1
windows ×1