[gambit-list] a simple question for optimization

김진우 snifel0 at gmail.com
Fri Apr 10 17:08:08 EDT 2015


Hi gambit users

I am trying to verify that a program written in Gambit-C scheme is as fast
as equivalent C program.

I tried to make a scheme version of the following C++ program which is;

*#include <iostream>*
*#include <cmath>*
*#include <cstdio>*
*#include <ctime>*
*#include <cstdlib>*
*#include <iomanip>  *

*using namespace std;*

*double f(double x);*

*int main(int argc, char* argv[]) {*
*  clock_t start;*
*  start = clock();*
*  double duration;*
*  double sum = 0;*
*  long n = atoi(argv[1]);*
*  double x;*
*  for(long i = 1; i <= n ;i++) {*
*    x = (i - 0.5) / n;*
*    sum += 4.0/(1.0+x*x);*
*  }*
*  sum /= n;*
*  cout << setprecision(17) << sum << endl << endl;*

*  duration = ( clock() - start ) / (double) CLOCKS_PER_SEC;*
*  cout << duration <<'\n';*
*  return 0;*
*}*

*double f(double x) {*
*  return 4.0/(1.0 + x*x);*
*}*

and my best so far is
*#!/usr/bin/env gsi-script*
*(declare*
*  (not safe)*
*  (mostly-flonum))*
*(define (main arg)*
*  (let ((k (string->number arg)))*
*    (pretty-print (time (cpi (exact->inexact k))))))*
*(define (cpi n)*
*  (letrec ((rec (lambda (i sum)*
*                  (let* ((x (fl/ (fl- i 0.5) n))*
*                         (summand (fl/ 4.0 (fl+ 1.0 (fl* x x)))))*
*                    (if (fl> i n)*
*                        (fl/ sum n)*
*                        (rec (fl+ i 1.0) (fl+ sum summand)))))))*
*    (rec 0.0 0.0)))*

and the result is poor: 0.043s vs 0.145s
*server at HP-Proliant-MicroServer:~/speedtest$ ls*
*pi.cpp  pi.scm*
*server at HP-Proliant-MicroServer:~/speedtest$ g++ -o pi-cpp pi.cpp*
*server at HP-Proliant-MicroServer:~/speedtest$ gsc -exe -o pi-scm pi.scm*
*server at HP-Proliant-MicroServer:~/speedtest$ time ./pi-cpp 1000000*
*3.1415926535897643*

*0.038903*

*real 0m0.043s*
*user 0m0.042s*
*sys 0m0.004s*
*server at HP-Proliant-MicroServer:~/speedtest$ time ./pi-scm 1000000*
*(time (cpi (exact->inexact k)))*
*    128 ms real time*
*    128 ms cpu time (127 user, 2 system)*
*    182 collections accounting for 67 ms real time (72 user, 1 system)*
*    224000448 bytes allocated*
*    341 minor faults*
*    no major faults*
*3.1415966535897644*

*real 0m0.145s*
*user 0m0.136s*
*sys 0m0.009s*
*server at HP-Proliant-MicroServer:~/speedtest$ *

So.. I guess my scheme version is not equivalent to the original C++
program,
but I'm having trouble figuring out why

any help will be appreciated

any comment, any suggestion..
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.iro.umontreal.ca/pipermail/gambit-list/attachments/20150411/ef369962/attachment.htm>


More information about the Gambit-list mailing list