pi_riemann.c ダウンロード/コピー

pi_riemann.c をダウンロード

pi_riemann.c
pi_riemann.c
  1/*
  2 * Independent C benchmark for midpoint-Riemann integration of sqrt(1-x*x).
  3 * Build: cc -O3 -std=c11 -D_POSIX_C_SOURCE=200809L pi_riemann.c -lm -o pi_riemann
  4 * Windows (MSVC): cl /O2 /std:c11 pi_riemann.c /Fe:pi_riemann.exe
  5 * Run:   ./pi_riemann --nmax 10000000 --repeat 5
  6 */
  7
  8/*
  9概要:
 10    中点リーマン和による円周率計算の独立したC言語ベンチマークプログラムです。
 11詳細説明:
 12    関数 sqrt(1 - x*x) を用いて円周率を近似計算し、その実行時間を計測します。
 13関連リンク:
 14    pi_riemann_usage
 15*/
 16
 17#ifndef _WIN32
 18#ifndef _POSIX_C_SOURCE
 19#define _POSIX_C_SOURCE 200809L
 20#endif
 21#endif
 22
 23#ifdef _WIN32
 24#include <windows.h>
 25#endif
 26
 27#include <math.h>
 28#include <stdio.h>
 29#include <stdlib.h>
 30#include <string.h>
 31#include <time.h>
 32
 33static double now_seconds(void) {
 34    /*
 35    概要:
 36        現在時刻を秒単位で取得します。
 37    詳細説明:
 38        Windows環境では QueryPerformanceCounter を使用し、その他のPOSIX環境では
 39        clock_gettime を使用して高分解能な時刻を取得します。
 40        タイマーが利用できない場合はエラーを出力し、プログラムを終了します。
 41    戻り値:
 42        :returns: 基準時からの経過秒数。
 43        :rtype: double
 44    */
 45#ifdef _WIN32
 46    LARGE_INTEGER counter, frequency;
 47    if (!QueryPerformanceFrequency(&frequency) ||
 48        !QueryPerformanceCounter(&counter)) {
 49        fprintf(stderr, "High-resolution timer unavailable.\n");
 50        exit(EXIT_FAILURE);
 51    }
 52    return (double)counter.QuadPart / (double)frequency.QuadPart;
 53#else
 54    struct timespec ts;
 55    if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
 56        perror("clock_gettime");
 57        exit(EXIT_FAILURE);
 58    }
 59    return (double)ts.tv_sec + 1.0e-9 * (double)ts.tv_nsec;
 60#endif
 61}
 62
 63static double pi_midpoint(long long nmax) {
 64    /*
 65    概要:
 66        中点リーマン和を用いて円周率を計算します。
 67    詳細説明:
 68        関数 sqrt(1.0 - x * x) を区間 0 から 1 まで積分し、4倍することで円周率を求めます。
 69    引数:
 70        :param nmax: 積分の分割数。
 71        :type nmax: long long
 72    戻り値:
 73        :returns: 計算された円周率の近似値。
 74        :rtype: double
 75    */
 76    const double dx = 1.0 / (double)nmax;
 77    double total = 0.0;
 78    for (long long i = 0; i < nmax; ++i) {
 79        const double x = ((double)i + 0.5) * dx;
 80        total += sqrt(1.0 - x * x);
 81    }
 82    return 4.0 * dx * total;
 83}
 84
 85static int compare_double(const void *a, const void *b) {
 86    /*
 87    概要:
 88        qsort用のdouble型比較関数です。
 89    詳細説明:
 90        2つのdouble型ポインタを受け取り、その値の大小関係を比較します。
 91        昇順のソートに使用されます。
 92    引数:
 93        :param a: 比較する1つ目の値へのポインタ。
 94        :type a: const void *
 95        :param b: 比較する2つ目の値へのポインタ。
 96        :type b: const void *
 97    戻り値:
 98        :returns: aがbより大きい場合は正の数、小さい場合は負の数、等しい場合は0。
 99        :rtype: int
100    */
101    const double da = *(const double *)a;
102    const double db = *(const double *)b;
103    return (da > db) - (da < db);
104}
105
106static void usage(const char *program) {
107    /*
108    概要:
109        プログラムの使用方法を標準エラー出力に表示します。
110    引数:
111        :param program: 実行時のプログラム名。
112        :type program: const char *
113    */
114    fprintf(stderr, "Usage: %s [--nmax positive-integer] [--repeat positive-integer]\n", program);
115}
116
117int main(int argc, char **argv) {
118    /*
119    概要:
120        プログラムのエントリポイントです。
121    詳細説明:
122        コマンドライン引数を解析して nmax と repeat を設定し、
123        指定された回数だけ pi_midpoint 関数を呼び出して円周率を計算します。
124        各実行の所要時間を計測し、中央値などの統計情報とともに結果を標準出力に表示します。
125    引数:
126        :param argc: コマンドライン引数の数。
127        :type argc: int
128        :param argv: コマンドライン引数の文字列配列。
129        :type argv: char **
130    戻り値:
131        :returns: 正常終了時は0、引数エラー時は2、メモリ確保エラー時は1。
132        :rtype: int
133    */
134    long long nmax = 1000000;
135    int repeat = 3;
136
137    for (int i = 1; i < argc; ++i) {
138        if (strcmp(argv[i], "--nmax") == 0 && i + 1 < argc) {
139            nmax = strtoll(argv[++i], NULL, 10);
140        } else if (strcmp(argv[i], "--repeat") == 0 && i + 1 < argc) {
141            repeat = (int)strtol(argv[++i], NULL, 10);
142        } else if (strcmp(argv[i], "--help") == 0) {
143            usage(argv[0]);
144            return 0;
145        } else {
146            usage(argv[0]);
147            return 2;
148        }
149    }
150    if (nmax < 1 || repeat < 1) {
151        usage(argv[0]);
152        return 2;
153    }
154
155    double *times = malloc((size_t)repeat * sizeof(*times));
156    if (times == NULL) {
157        fprintf(stderr, "Unable to allocate timing array.\n");
158        return 1;
159    }
160
161    double value = 0.0;
162    for (int r = 0; r < repeat; ++r) {
163        const double t0 = now_seconds();
164        value = pi_midpoint(nmax);
165        times[r] = now_seconds() - t0;
166    }
167    qsort(times, (size_t)repeat, sizeof(*times), compare_double);
168    const double median = (repeat % 2) ? times[repeat / 2]
169        : 0.5 * (times[repeat / 2 - 1] + times[repeat / 2]);
170
171    printf("Midpoint Riemann sum: nmax=%lld, repeat=%d\n", nmax, repeat);
172    printf("C                  pi=%.15f  abs.error=%.3e  median=%.6f s  min=%.6f s\n",
173           value, fabs(value - acos(-1.0)), median, times[0]);
174    free(times);
175    return 0;
176}