c++ - 加速 Monte Carlo Pi

标签 c++ multithreading

我编写了一个 C++ 程序,用于通过“将随机点放入四分之一圆中并计算它们等”来计算圆周率。现在我的程序在我看来有点慢,我想过一些改进来加快它的速度(源代码在下面)。
我的第一个想法是使用 OpenMP 使其成为多线程的,即将 (I) 和 (II) 之间的代码拆分为多个线程,这样我就有了近十倍的轮数,而不必等待更长的时间(在八核系统上)。
我的另一个想法是使用全局变量和指针,这样我只需要复制指针而不是整数元组。缺点是 (idk)?
那么,我还能做些什么来加快程序的速度呢?我主要使用 Windows,但我也可以使用 Unix/Linux。
非常感谢!

代码部分:

    #include <cstdlib>
    #include <iostream>
    #include <tuple>
    #include <math.h>
    #include <time.h>
    #include <omp.h>
    #include <sys/time.h>

    #define RAND_MAX 32000
    #define LOOPS 1000000

    inline std::tuple<int, int> Throw_points(void)
    {

        int i = 0, j = 0;
        i = rand() % 1000;
        j = rand() % 1000;
        return std::make_tuple(i, j);
    }

    inline bool is_in_circle(std::tuple<int, int> point)
    {
        if ((pow(std::get<0>(point), 2) + pow(std::get<1>(point), 2)) <= pow(1000, 2))
            return true;
        else
            return false;
    }

    inline double pi(void)
    {
        srand(time(NULL));
        long long int in_circle = 0;
        long long int out_circle = 0;
        for (int i = 0; i < LOOPS; i++)
        {
            if (is_in_circle(Throw_points()))
                in_circle++;
            out_circle++;
        }
        return double(in_circle) / double(out_circle) * 4;
    }

通过pi()调用

最佳答案

我只是玩了一下。实际上,对原始帖子(包括我自己的)的评论中的所有建议几乎没有任何区别。

但是,摆脱元组

inline void Throw_points(int&i, int&j)
{
    i = rand() % 1000;
    j = rand() % 1000;
}

inline bool is_in_circle(int i, int j)
{
    return i*i + j*j < 1000000;        
}

将程序加速了 5 倍。

我使用了这里的 boost::progress_timer 解决方案,顺便说一句:How to get the time elapsed running a function in C++

关于c++ - 加速 Monte Carlo Pi,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19912701/

相关文章:

c++ - 将 C++ 模板类型 T 修改为 "long T"?

c++ - 静态/静态本地 SSE/AVX 变量是否阻塞了 xmm/ymm 寄存器?

python - 如何在 Python 中将 DWORD 转换为字符串

python - 在 Python 中,创建和管理线程的首选方式是什么?

c - 易变的变量

C++ - 套接字服务器线程

c++ - 如何安全地销毁一个经常被两个不同线程访问的对象?

java - 为方法调用的异步执行创建自定义 "Asynch"注释是个好主意吗?

使用 newCachedThreadPool() 时,Java 并行流未使用最佳线程数

c++ - 抄袭者的异常行为