关于swap, max 的速度

我一直坚贞地用着这种小的stl, 但是总是有人说它们很慢。 这里测试一下速度

首先是swap

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <time.h>
using namespace std;
int main()
{
    int s = clock();
    int a, b, c;
    for(int i = 1; i <= 1000000000; i ++)//swap(a, b);
       // a ^= b ^= a ^= b;
         c = a, a = b, b = c;
    int t = clock();
    cout<<t - s<<endl;
    system("pause");
    return 0;
}
用swap, 亦或 和领取一个变量赋值

十亿次, int 的时候 按照行数分别为: 6328,  6890, 2922

10亿次, long long 时分别为: 7047,7500, (……),  3812

所以说结果是?

一直都据说是很快的^ 反而是最慢的。。。 最快的是最基本的赋值法!

所以以后还是少用swap了吧。。毕竟速度差了一倍还要多。




然后是更加常用的max

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <time.h>
using namespace std;
int main()
{
    int s = clock();
    int a, b, c;
    for(int i = 1; i <= 100000000; i ++)//c = max(a, b);
       c = a > b ? a : b;
    int t = clock();
    cout<<t - s<<endl;
    system("pause");
    return 0;
}

懒得测十亿次了。。

一亿次下int, 分别为453 和281

longlong 分别为 656 和 484

好吧 也的确是有差距的T T


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值