Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting array subsets efficiently

Is there an efficient way to take a subset of a C# array and pass it to another peice of code (without modifying the original array)? I use CUDA.net which has a function which copies an array to the GPU. I would like to e.g. pass the function a 10th of the array and thus copy each 10th of the array to the GPU seperately (for pipelining purposes).

Copying the array in this way should be as efficient as copying it in one go. It can be done with unsafe code and just referencing the proper memory location but other than that I'm not sure. The CopyTo function copies the entire array to another array so this does not appear useful.

like image 696
Morten Christiansen Avatar asked Nov 06 '08 12:11

Morten Christiansen


People also ask

How do you subset an array?

A subsequence/ subset of an array can be formed by choosing some (may be 0, 1, 2, ... or equal to size of array) elements out of all the possible array elements, in the same order in which they appear in the original array. Let us consider the array = {a, b, c}.

How do you get all subarrays of an array?

We can use substr function to find the all possible sub array.

How do you find the number of subsets in a set?

How many subsets and proper subsets does a set have? If a set has “n” elements, then the number of subset of the given set is 2n and the number of proper subsets of the given subset is given by 2n-1.


3 Answers

Okay, I'd misunderstood the question before.

What you want is System.Buffer.BlockCopy or System.Array.Copy.

The LINQ ways will be hideously inefficient. If you're able to reuse the buffer you're copying into, that will also help the efficiency, avoiding creating a new array each time - just copy over the top. Unless you can divide your "big" array up equally though, you'll need a new one for the last case.

like image 87
Jon Skeet Avatar answered Sep 26 '22 17:09

Jon Skeet


I'm not sure how efficient this is but...

int[] myInts = new int[100];

//Code to populate original arrray

for (int i = 0; i < myInts.Length; i += 10)
{
    int[] newarray = myInts.Skip(i).Take(10).ToArray();
    //Do stuff with new array
}
like image 20
Eoin Campbell Avatar answered Sep 24 '22 17:09

Eoin Campbell


You could try Marshal.Copy if you need to go from an array of bytes to an unmanaged pointer. That avoids creating unsafe code yourself.

Edit: This would clearly only work if you reimplement their API. Sorry - misunderstood. You want an efficient subarray method.

It strikes me that what you really want is an api in the original class of the form

void CopyToGpu(byte[] source, int start, int length);
like image 40
plinth Avatar answered Sep 25 '22 17:09

plinth