从一个内存中复制元素到另一个内存

3
我在面试中被问到了这个问题,它看起来很简单,但我想确认一下我对它的功能理解是否正确。
f (char *p, char *q, int n)
{
    int i1 = n >> 2;
    int i2 = n & 3;

    switch (i2) 
    {
        do {
            *q++ = *p++;
            case 3:  *q++ = *p++;
            case 2:  *q++ = *p++;
            case 1:  *q++ = *p++;
            case 0:  ;
        } while (i1--);
    }
}

我在面试中被问到以下问题:
  1. 这个函数是用来干什么的?
  2. 为什么有人会写出那么复杂的代码?
  3. 有没有其他方法可以写得更简单、更快速一些?
我的回答如下:
  1. This function copies the number of elements from the memory where *P is pointing to the memory where *q is pointing.

  2. if you will write it with for loop as below (writing only loop)

    for(i=0;i<n;i++)
       *q++ = *p++;
    

    then the compiler taking more MIPS/time in condition checking. In this it will first subtract i from n and then checks is I non zero ? In the given code while loop maintain condition only 1 condition if i1 is non-zero ? So in while loop there is less condition checking.

  3. We can write as:

    f (char *p, char *q, int n)
    {
      for(i=n;i--;)
        *q++ = *p++;
    }
    

    It seems simple and faster to me.

请给我你的意见。

3
一条很好的建议——在发布代码到这里之前,请先在你的电脑上的文本编辑器中写好代码,然后再将其复制到你的问题中。这样你可以注意到一些拼写错误,并保证正确地缩进。 - elyashiv
看起来有人错误地编辑了你的代码? 应该是 do { switch() { ... }; } while(); - dragon135
1个回答

1
首先,在您的答案中,您似乎没有考虑到n>>2会在循环之前将n整数除以4。 然后,您没有检查第二个条件,即如果n % 4 == 0,则不复制该值。
  • 从p到q复制7个字节并忽略第8个字节,直到n/4个字节;
  • 它在执行任务时非常高效。使用&3而不是%4可能更快,并且使用>> 2而不是/4可能会更快;只有可能,因为编译器或C语言可能被设计为自动为您进行优化;
  • 我会给出这样的东西

    f (char *p, char *q, int n)
    {
    int i1 = n >> 2; //i1 = n / 3;
    int i2 = n & 3;  //i2 = n & 0b111 = n % 4;
    
    for(; i1 + 1 ; --i) {
        *q++ = *p++;
        if (i2) *q++ = *p++;            
        } 
    }
    
  • 提到for循环更易于理解且同样高效,

  • 并且将switch语句更改为单个if语句更清晰,最可能具有相似的性能。

  • 然后,我会指出我添加了位运算的注释以使其功能更清晰。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接