c - C结构或数组设计几何库
问题描述
我需要编写一个库来管理 C 中 2D 空间中点的几何变换。这些点将以形状聚合,我希望能够(自动)矢量化通过 OpenMP 对完整形状的处理。
我坚持的问题是继续声明要点的最佳方式:
typedef __attribute__((aligned(8))) float point_t[2];
或者
typedef struct point_t
{
float x, y;
} point_t;
知道了,以后我会使用一个盒子类型:
typedef __attribute__((aligned(64))) point_t box_t[4];
从编程的角度来看,它box[1].y
比box[1][1]
(矩形框第二个点的 y 坐标)更易读。现在,编译器会理解结构只是数组的一个很好的处理程序并相应地进行向量化吗?
解决方案
无论如何,你将传递给你的向量函数的是一个float*
. 您唯一的问题是确保您的x
,y
结构正确映射到您的 2 元素数组。
即使 C 标准不保证结构中不会有填充(开头除外),我看不出编译器不按照您的预期进行操作的原因。我很确定 GNU 和 Microsoft 都会默认将这两个浮点数打包成 8 个字节。
我想说一个简单的typedef struct { float x,y; } point_t;
应该是安全的。
为了安全起见,您可以添加一个偏执检查,例如:
struct { float x,y; } coords; // expected to map to float[2]
float vector[2];
assert (offsetof(coords,x) == 0); // already guaranteed by the C standard
assert (offsetof(coords,y) == sizeof(float));
assert (sizeof(coords) == sizeof(vector));
如果该代码运行良好(或者更确切地说是编译器优化了该代码),我看不出它以后会如何对你玩肮脏的把戏。
推荐阅读
- jqgrid - 引导选项卡内的 jqGrid 不会显示
- python - 我使用 Python 创建了一个 CSV 文件。但是体积很大
- python - 根据开始和结束字符python在列表中附加行
- scala - 任何列中带有 nan 的 spark/scala 删除行
- json-api - crnk json 实现 Java API 文档
- avisynth - AviSynth AvsP 溶解不起作用
- r - 从 R Markdown 文档中删除所有代码块
- c# - WinForms:如何防止面板随窗口内容滚动?
- python - Python:将向量插入矩阵
- docker - Traefik 允许自定义域