逖靖寒的世界

每天进步一点点

导航

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

 

 1using System;
 2using System.Collections.Generic;
 3using System.Text;
 4
 5namespace 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毫秒。

posted on 2007-11-22 13:41  逖靖寒  阅读(2669)  评论(31编辑  收藏  举报