Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

c++ - How to transform this memcpy into a for?

What is the difference between these two?


for (int i = 0; i < numSamples; i++) {
    mData[sampleIndex++] = *buffer++ * (1.0f / 32768);
}

and

memcpy(&mData[sampleIndex], buffer, (numSamples * sizeof(float)));

If I understood correct, the first copies numSamples float values to mData, one by one. The second one, copies numSamples*sizeof(float) bytes to mData. Since we're copying numSaples * number of bytes on float, I think they do the same thing, but the first one actually multiplies things before passing to mData.

So, is there a way to transform the memcpy into a for? Something like:

for (int i = 0; i < numSamples * sizeof(float); i++) {
    //What to put here?
}

Context:

const int32_t   mChannelCount;
const int32_t   mMaxFrames;
int32_t sampleIndex;
float          *mData;
float *buffer;
question from:https://stackoverflow.com/questions/65945183/how-to-transform-this-memcpy-into-a-for

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

What is the difference between these two?

for (int i = 0; i < numSamples; i++) {
  mData[sampleIndex++] = *buffer++ * (1.0f / 32768);
}
// and
memcpy(&mData[sampleIndex], buffer, (numSamples * sizeof(float)));

These are quite different given the * (1.0f / 32768);. I assume the code compare is setting the scaling difference aside. @Thomas Matthews.

  • Important: buffer, sampleIndex has different values after the for loop.

  • *buffer++ needs no code change should the type of buffer change. * sizeof(float) obilgies a code change. Could have used * sizeof *buffer.

  • mempcy() is optimized code per that platform. for() loops can only do so much. In particular, mempcy() assumes mData, buffer do not overlap. The for() loop may not be able to make that optimization.

  • This for uses int indexing where memcpy() uses size_t. Makes a difference with huge arrays.

  • memcpy() tolerates an unaligned pointers. mData[sampleIndex++] = *buffer++ .. does not.

"the first copies numSamples float values to mData, one by one. " is a not certain. A smart compiler may be able to make certain parallel copies depending on the context and act as if copying was done one by one.

Post the entire block of code/function that uses these 2 approaches for a better compare.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...