Efficient reading of floating point arrays

G

Guest

I'm new to C#, so please forgive me if this is elementary. I have a file
that consists of, say, one thousand (4-byte) floating points, and I'd like to
read it into an array of floats as efficiently as possible. In C/C++ I'd
simply malloc an array of bytes, read them into my allocated buffer, and cast
the pointer to the buffer as a pointer to a float. In C#, I can read in the
array of bytes like so:

FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] buffer = r.ReadBytes(4000);

Now how would I convert this to an array of 1000 floating points without
converting 4 bytes at a time? Or, is there a way to read 1000 floats
directly from the file without going one at a time? Currently, I'm doing
this:

FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
float[] buffer = new float[1000];

for (int i=0;i<1000;i++)
{
buffer = r.ReadSingle();
}

This seems awfully inefficient. Is there a better way?

Thank you,

Keith Kingsley
 
J

Jon Skeet [C# MVP]

Keith Kingsley said:
I'm new to C#, so please forgive me if this is elementary. I have a file
that consists of, say, one thousand (4-byte) floating points, and I'd like to
read it into an array of floats as efficiently as possible. In C/C++ I'd
simply malloc an array of bytes, read them into my allocated buffer, and cast
the pointer to the buffer as a pointer to a float. In C#, I can read in the
array of bytes like so:

FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] buffer = r.ReadBytes(4000);

Not that you need to use BinaryReader at all, of course - you can just
use Stream.Read (taking care to note the number of bytes actually
read).
Now how would I convert this to an array of 1000 floating points without
converting 4 bytes at a time? Or, is there a way to read 1000 floats
directly from the file without going one at a time? Currently, I'm doing
this:

FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
float[] buffer = new float[1000];

for (int i=0;i<1000;i++)
{
buffer = r.ReadSingle();
}

This seems awfully inefficient. Is there a better way?


That looks like the best way to me, to be honest. If you're worried
about efficiency, have you actually measured the current performance
and found it to be inadequate?

Buffer.BlockCopy may well work for you, but I don't think it's as clean
a way as the above, personally.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top