加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

C++判断整数是否为偶数的两种方法

(2019-03-18 10:38:24)
标签:

判断

偶数

方法1:采用求余方法%
int a = 100;
bool b;
b = (a%2 ==0);

方法2:采用位逻辑符号&
int a = 100;
bool b;
b = !(a&1); // 注意要取反

到底哪个速度快?

#include "stdlib.h" // CPU 端分配内存给变量,显示不出<>,用引号替代
#include "stdio.h" // printf
#include "time.h"  //clock_t
#include "chrono" 

using namespace std; // 必要,放在前
using namespace chrono; // 必要

int main()
{
int n = 200000;
int a[200000];
bool b[200000];

for (int i = 0; i < n; i++)
a[i] = i;

for (int i = 0; i < n; i++)
b[i] = true;

auto start = system_clock::now();

for (int i = 0; i < n; i++)
b[i] = (a[i] % 2 == 0);
auto end = system_clock::now();

auto duration = duration_cast(end - start);
printf("(CPU)  cost time: %f ms\n", 1000 * double(duration.count())*microseconds::period::num / microseconds::period::den);


start = system_clock::now();

for (int i = 0; i < n; i++)
b[i] = !(a[i] & 1);
end = system_clock::now();

duration = duration_cast(end - start);
printf("(CPU)  cost time: %f ms\n", 1000 * double(duration.count())*microseconds::period::num / microseconds::period::den);

return 0;
}

自己测完就清楚了。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有