在C#中用常数对大型数组进行乘/加的高性能方法是什么? [英] What is a high performance way of multiplying/Adding a big array of numbers with a constant in c#?

查看:75
本文介绍了在C#中用常数对大型数组进行乘/加的高性能方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构(类),可以在数组中保留大量数字(浮点数,双精度数,整数,字节).

I have a structure (class) that keeps very large number of numbers (either float, double, int, byte) in an array.

现在,我想采用一种非常高性能的方法在此数组上应用一些原始操作(加/减/除/乘以一个常数).

Now I want to have very high performance approach to apply some primitive operations (Add/Subtract/Divide/Multiply with a constant) on this array.

此数组位于连续的内存中,因此例如使用Buffer.BlockCopy复制它.

This arrays is on a continuous piece of memory so for example for copying it I am using Buffer.BlockCopy.

但是添加一个常数或与一个常数相乘又怎么办呢?

But what about adding a constant or multiplying with a constant?

首选是使用指针遍历数组.您为此建议什么其他方法?

The first choice is to walk through the array using pointers. What other approaches do you suggest for this?

推荐答案

不确定使用指针(不安全)的性能.

Using pointer (unsafe) is not certain to be more performant.

为什么不从普通的 for(int index = 0; index< data.Lenght; index ++)循环开始,看看它是否满足您的要求.

Why don't you start with a normal for(int index = 0; index < data.Lenght; index++) loop and see if it meets your requirements.

当然,下一步将是并行处理:

And of course, the next step would be processing in parallel :

 Parallel.For(0, data.Length, i => data[i] *= myFactor);

这篇关于在C#中用常数对大型数组进行乘/加的高性能方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆