相关疑难解决方法(0)

获得π值的最快方法是什么?

我正在寻找获得π值的最快方法,作为个人挑战.更具体地说,我使用的方法不涉及使用#define常量M_PI,或者对数字进行硬编码.

下面的程序测试了我所知道的各种方式.从理论上讲,内联汇编版本是最快的选择,但显然不便于携带.我已将其作为基线与其他版本进行比较.在我的测试中,使用内置4 * atan(1)函数,在GCC 4.2上版本最快,因为它会自动将其折叠atan(1)为常量.根据-fno-builtin指定,atan2(0, -1)版本最快.

这是主要的测试程序(pitimes.c):

#include <math.h>
#include <stdio.h>
#include <time.h>

#define ITERS 10000000
#define TESTWITH(x) {                                                       \
    diff = 0.0;                                                             \
    time1 = clock();                                                        \
    for (i = 0; i < ITERS; ++i)                                             \
        diff += (x) - M_PI;                                                 \
    time2 = clock();                                                        \
    printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1));   \
}

static inline double
diffclock(clock_t time1, clock_t time0)
{ …
Run Code Online (Sandbox Code Playgroud)

language-agnostic unix algorithm performance pi

315
推荐指数
21
解决办法
5万
查看次数

标签 统计

algorithm ×1

language-agnostic ×1

performance ×1

pi ×1

unix ×1