C#/Linq 中的二维数组求和
我有一个二维整数数组。我想编写一个优化且快速的代码来对二维数组的所有列求和。
有什么想法我可以如何使用 LINQ/PLINQ/TASK 并行化来做到这一点?
前任:
private int[,] m_indexes = new int[6,4] { {367, 40, 74, 15},
{535, 226, 74, 15},
{368, 313, 74, 15},
{197, 316, 74, 15},
{27, 226, 74, 15},
{194, 41, 74, 15} };
I have a two dimensional array of integers. I would like to write an optimized and fast code to sum all the columns of the two dimensional array.
Any thoughts how I might be able to do this using LINQ/PLINQ/TASK parallelization ?
Ex:
private int[,] m_indexes = new int[6,4] { {367, 40, 74, 15},
{535, 226, 74, 15},
{368, 313, 74, 15},
{197, 316, 74, 15},
{27, 226, 74, 15},
{194, 41, 74, 15} };
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的并行实现:
此代码显然可以“通用化”(使用
m_indexes.GetLength(0)
和m_indexes.GetLength(1)
)。LINQ:
如果您确实需要在此处优化性能,请务必在此处分析真实数据。
另外,如果您确实关心优化性能,请尝试加载数组,以便跨行求和。通过这种方式,您将获得更好的局部性缓存性能。
The simplest parallel implementation:
This code can obviously be "generalized" (use
m_indexes.GetLength(0)
andm_indexes.GetLength(1)
).LINQ:
Be sure to profile on real-world data here if you truly need to optimize for performance here.
Also, if you truly care about optimizing for performance, try to load up your array so that you summing across rows. You'll get better locality for cache performance that way.
或者也许没有 for :
Or maybe without for's :
简单的 LINQ 方式:
并行化可能不值得。如果您需要按索引访问数组,则需要花费一些周期进行边界检查,因此,与性能一样,请务必对其进行测量。
Straightforward LINQ way:
It might not be worth it to parallelize. If you need to access the array by index, you spend some cycles on bounds checking, so, as always with performance, do measure it.