]> www.ginac.de Git - ginac.git/blob - doc/examples/compile1.cpp
[BUGFIX] Fix crash in parser.
[ginac.git] / doc / examples / compile1.cpp
1 #include <ctime>
2 #include <iostream>
3 #ifdef IN_GINAC
4 #include "ginac.h"
5 #else
6 #include <ginac/ginac.h>
7 #endif
8 using namespace std;
9 using namespace GiNaC;
10
11 /*
12  * Demonstrates the use of compile_ex.
13  *
14  * Compiles a small expression as C code via compile_ex and evaluates the
15  * expression numerically. The evalation speed is timed and compared to the
16  * evaluation of the original GiNaC expression.
17  *
18  */
19
20 int main()
21 {
22         // Define some expression
23         symbol x("x");
24         ex expr = sin(x);
25  
26         // Some variables for timing
27         time_t start, end;
28         double cpu_time_used;
29
30         // Our function pointer that points to the compiled ex
31         FUNCP_1P fp;
32
33         // Optionally, compile with custom compiler flags:
34         // setenv("CXXFLAGS", "-O3 -fomit-frame-pointer -ffast-math", 1);
35         compile_ex(expr, x, fp);
36
37         // Do some (not necessarily meaningful ;-)) numerical stuff ...
38
39         cout << "Doing numerics with compile_ex ..." << endl;
40
41         // First using compile_ex
42         {
43                 double result = 0.0;
44                 double point = 0.2;
45                 start = clock();
46                 for (int i=0; i<100000; ++i) {
47                         point += 0.001;
48                         result += fp(point);
49                 }
50                 end = clock();
51
52                 // Show the result
53                 cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
54                 cout << "result = " << result << " in " << cpu_time_used << " seconds" << endl;
55         }
56
57         cout << "Doing numerics without compile_ex ..." << endl;
58
59         // Then without compile_ex
60         {
61                 ex result = 0.0;
62                 ex point = 0.2;
63                 start = clock();
64                 for (int i=0; i<100000; ++i) {
65                         point += 0.001;
66                         result += sin(point);
67                 }
68                 end = clock();
69
70                 // Show the other result
71                 cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
72                 cout << "result = " << result << " in " << cpu_time_used << " seconds" << endl;
73         }
74
75         return 0;
76 }