一个并行程序

本文通过比较迭代方法与并行方法在查找大量素数过程中的效率,展示了并行计算在大规模数据处理任务中的优势。通过实现并行和迭代两种查找素数的算法,实验证明了并行方法在查找大素数时显著提高了计算速度。
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace GetPrimes
{
    internal class ProcessDataInParallel
    {
        private static void Main(string[] args)
        {
            int maxPrimes = 1000000;
            int maxNumber = 20000000;
            long primesFound = 0;
            Console.WriteLine("Iterative");
            Stopwatch watch = new Stopwatch();
            watch.Start();

            for (UInt32 i = 0; i < maxNumber; ++i)
            {
                if (IsPrime(i))
                {
                    Interlocked.Increment(ref primesFound);
                    if (primesFound > maxPrimes)
                    {
                        Console.WriteLine("Last prime found:{0:N0}", i);
                        break;
                    }
                }
            }
            watch.Stop();
            Console.WriteLine("Found {0:N0} primes in {1}", primesFound, watch.Elapsed);

            watch.Reset();
            primesFound = 0;
            Console.WriteLine("Parallel");
            watch.Start();

            //in order to stop the loop, there is an
            //overload that takes Action<int, ParallelLoopState>
            Parallel.For(0, maxNumber, (i, loopState) =>
            {
                if (IsPrime((UInt32)i))
                {
                    Interlocked.Increment(ref primesFound);
                    if (primesFound > maxPrimes)
                    {
                        Console.WriteLine("Last prime found:{0:N0}", i);
                        loopState.Stop();
                    }
                }
            });
            
            watch.Stop();
            Console.WriteLine("Found {0:N0} primes in {1}", primesFound, watch.Elapsed);
            Console.ReadKey();
        }
        
        public static bool IsPrime(UInt32 number)
        {
            //check for evenness
            if (number % 2 == 0)
            {
                if (number == 2)
                {
                    return true;
                }

                return false;
            }

            //don’¡¥t need to check past the square root
            UInt32 max = (UInt32)Math.Sqrt(number);
            for (UInt32 i = 3; i <= max; i += 2)
            {
                if ((number % i) == 0)
                {
                    return false;
                }
            }

            return true;
        }
    }
}


运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值