关于使用位操作与使用取模操作求奇偶数的性能比较。

 

 1 using  System;
 2 using  System.Collections.Generic;
 3 using  System.Text;
 4
 5 namespace  ConsoleApplication44
 6 {
 7    class Program
 8    {
 9        static void Main(string[] args)
10        {
11            int a = 55877554;
12            int len = 500000000;
13
14            DateTime start1 = DateTime.Now;
15
16            for (int i = 0; i < len; i++)
17            {
18                OddEven.IsEven(a);
19            }

20
21            TimeSpan ts1 = DateTime.Now - start1;
22
23            Console.WriteLine("使用位操作的时间:" + ts1.TotalMilliseconds);
24
25            DateTime start2 = DateTime.Now;
26
27            for (int i = 0; i < len; i++)
28            {
29                Mod2.IsEven(a);
30            }

31
32            TimeSpan ts2 = DateTime.Now - start2;
33
34            Console.WriteLine("使用求模操作的时间:" + ts2.TotalMilliseconds);
35        }

36    }

37
38    /// <summary>
39    /// 判断一个整数是奇数还是偶数。使用位操作
40    /// </summary>

41    static class OddEven
42    {
43        static public bool IsEven(int a)
44        {
45            return ((a & 1== 0);
46        }

47
48        static public bool IsOdd(int a)
49        {
50            return !IsEven(a);
51        }

52    }

53
54    /// <summary>
55    /// 判断一个整数是奇数还是偶数。使用求模操作
56    /// </summary>

57    static class Mod2
58    {
59        static public bool IsEven(int a)
60        {
61            return ((a % 2== 0);
62        }

63
64        static public bool IsOdd(int a)
65        {
66            return !IsEven(a);
67        }

68    }

69}

70


这个例子运行的结果还是位操作更快。

时间分别为3381毫秒和3974毫秒。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值