sample code /calculate PI (转)

using System;
using System.Math;

namespace PiWithMonteCarlo
{
    /// <summary>
    /// Trivial, synchronous calculation algorithm
    /// </summary>
    public static class TrivialPiCalculator
    {
        public static double Calculate(int iterations)
        {
            int inCircle = 0;
            var random = new Random();
            for (int i = 0; i < iterations; i++)
            {
                var a = random.NextDouble();
                var b = random.NextDouble();

                // Strictly speaking, we do not need Sqrt here. We could simply drop it and still get the
                // same result. However, this sample should demonstrate some perf topics, too. Therefore
                // it stays there just so the program has to do some math.
#if LANG_EXPERIMENTAL
                var c = Sqrt(a * a + b * b);
#else
                var c = Math.Sqrt(a * a + b * b);
#endif
                if (c <= 1)
                {
                    inCircle++;
                }
            }

            return ((double)inCircle / iterations) * 4;
        }
    }
}

using System;
using System.Diagnostics;

namespace PiWithMonteCarlo.TestDriver
{
    class Program
    {
        static void Main(string[] args)
        {
            var iterations = 20000000 * Environment.ProcessorCount;

            ExecuteAndPrint("Trivial PI Calculator", TrivialPiCalculator.Calculate, iterations);
            ExecuteAndPrint("\n(Stupid) Parallel.For PI Calculator", ParallelForPiCalculator.Calculate, iterations);
            ExecuteAndPrint("\nParallel.For PI Calculator", EnhancedParallelForPiCalculator.Calculate, iterations);
            ExecuteAndPrint("\nPLinq PI Calculator", PlinqPiCalculator.Calculate, iterations);
            ExecuteAndPrint("\nFast PI Calculator", FastPiCalculator.Calculate, iterations);
        }

        private static void ExecuteAndPrint(string label, Func<int, double> calculation, int iterations)
        {
            Console.WriteLine(label);
            PrintResult(Measure(() => calculation(iterations)), iterations);
        }

        private static void PrintResult(Tuple<double, TimeSpan> r, int iterations)
        {
            Console.WriteLine(
                "{0} ({1:#,##0.0000} sec for {2:#,##0} iterations = {3:#,##0.00} iter/sec)",
                r.Item1,
                r.Item2.TotalSeconds,
                iterations,
                iterations / r.Item2.TotalSeconds);
        }

        private static Tuple<T, TimeSpan> Measure<T>(Func<T> body)
        {
            var watch = new Stopwatch();
            watch.Start();
            var result = body();
            watch.Stop();
            return new Tuple<T, TimeSpan>(result, watch.Elapsed);
        }
    }
}

更多地址

http://www.software-architects.com/devblog/2014/09/22/C-Parallel-and-Async-Programming

时间: 2024-10-10 04:28:05

sample code /calculate PI (转)的相关文章

如何将经纬度利用Google Map API显示C# VS2005 Sample Code

原文 如何将经纬度利用Google Map API显示C# VS2005 Sample Code 日前写了一篇如何用GPS抓取目前所在,并回传至资料库储存,这篇将会利用这些回报的资料,将它显示在地图上,这个做法有两种,最简单的就是直接传值到Google Maps上. 举例来说,当我们知道经纬度后,只要将数据套到以下网址即可. http://maps.google.com/maps?q=25.048346%2c121.516396 在参数q=后面,就可以加上经纬度了. 25.048346是Lati

Compilation of OpenGL Redbook sample code

http://download.csdn.net/detail/gflytu/4110817#comment [email protected]:~/Downloads/redbook$ gcc -lglut -lGL -lGLU aaindex.c aaindex.c:(.text+0x2f7): undefined reference to `glutInit'aaindex.c:(.text+0x303): undefined reference to `glutInitDisplayMo

[Python] Calculate pi With MonteCarlo

import random import math m=int(raw_input("Please input the Number of Times:")) #Then Output n=10~10^m n=1 for j in xrange(m): n=n*10 Total=0 for i in xrange(n): x=random.random() y=random.random() if math.sqrt(x*x+y*y)<1.0: Total+=1 # print

sqoop sample code

本文使用的数据库是mysql的sample database employees. download url:https://launchpad.net/test-db/employees-db-1/1.0.6 然后根据ReadMe安装到自己的mysql数据库中. sqoop的安装: 下载地址:http://apache.dataguru.cn/sqoop/1.4.6/ sqoop-1.4.6.bin__hadoop-2.0.4-alpha.tar.gz sqoop-1.4.6.tar.gz 我

lua sample code analysis

What is a meta table a meta table has a __name attr whose value is name of metatable a meta table is stored in LUA_REGISTRYINDEX whose key is its name Code analysis Appl DUMP_STACK(L); /*{ "foo", "C:\\jshe\\codes\\mylualib\\test\\../build/v

使用MD5將字串加密 C# VS2005 Sample Code

MD5的加密已經出來很長一段時間了,也不是什麼特別的新技術,寫這篇的用意也有點像是給自己的一個Note,畢竟加密的功能不常用,最多寫成一個Class,未來去呼叫就好,怕自己也會忘記,所以把這個寫下來. 初步的UI設定如下: H執行是單純加密,而Salt執行則是跑Salted Hash的動作. 單純加密比較不好,如果被人猜到加密方法是採MD5,也沒有Salted,那會風險會高一點,而Salt的效果,因為多了一個Value去加密,除了前面的都要猜到外,還要知道Salted Value才可以.而Sal

python参数Sample Code

import time import datetime import getopt import sys try: opts, args = getopt.getopt(sys.argv[1:], "ho:", ["inputOCR=", "inputSpeech="]) except getopt.GetoptError: print ('Getopt Error!') sys.exit(1) for name, value in opts:

Stylecop code sample

StyleCopanalyzes C# source code to enforce a set of style and consistency rules. It can be run from inside of Visual Studio or integrated into an MSBuild project. StyleCop has also been integrated into many third-party development tools. StyleCop inc

Learning How To Code Neural Networks

原文:https://medium.com/learning-new-stuff/how-to-learn-neural-networks-758b78f2736e#.ly5wpz44d This is the second post in a series of me trying to learn something new over a short period of time. The first time consisted of learning how to do machine