swap 的速度

今天纠结于 swap 要显式地写出来还是写成函数。写成函数绝对要优美的多。

int main()
{
    int i;
    int a = 1, b = 2, tmp;
    for(i = 1; i <= 100000000; i++)
    {
        tmp = a;
        a = b;
        b = tmp;
    }
 
    return 0;
}

~~~ 一条分隔线 ~~~

void swap(int *a, int *b)
{
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
}
 
int main()
{
    int i;
    int a = 1, b = 2;
    for(i = 1; i <= 100000000; i++)
    {
        swap(&a, &b);
    }
 
    return 0;
}

显式的 swap 一次要 0.0000000035 秒。
函数的 swap 一次要 0.0000000057 秒。

我还试了一下 C++ 的 inline,发现没有速度的提升。

结论:用函数的 swap。这点速度损失没啥,然而一堆显式的 swap 不仅容易出错还极其影响心情。

10 thoughts on “swap 的速度

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">