aboutsummaryrefslogtreecommitdiff
path: root/bindings/java/examples/src/com/galois/ppaml/tracer/examples/Simple.java
blob: a69857325298c83205a75478491f97568fbaa8af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* Simple -- basic ppamltracer example
 * This file is in the public domain. */

package com.galois.ppaml.tracer.examples;

import com.galois.ppaml.tracer.Phase;
import com.galois.ppaml.tracer.Tracer;

public class Simple {

	protected Phase factPhase;

	protected Phase fibPhase;

	protected void go(Tracer tracer) {
		// Register the phases.
		factPhase = tracer.createPhase("fact");
		fibPhase = tracer.createPhase("fib");

		// Print factorials.
		System.out.print("Factorials:");
		for (int i = 0; i < 21; i++) {
			System.out.print(" " + fact(i));
		}
		System.out.println();

		// Print Fibonacci numbers.
		System.out.print("Fibonacci numbers:");
		for (int i = 0; i < 30; i++) {
			System.out.print(" " + fib(i));
		}
		System.out.println();

		// Finalize phases and exit.
		factPhase.close();
		fibPhase.close();
	}

	protected long fact(int n) {
		// Record that we're running inside the factorial phase.
		factPhase.start();
		// Compute the factorial.
		long result;
		if (n == 0) {
			result = 1;
		} else {
			result = n * fact(n - 1);
		}
		// Return the result.
		factPhase.stop();
		return result;
	}

	protected int fib(int n) {
		// Record that we're running inside the Fibonacci phase.
		fibPhase.start();
		// Compute the nth Fibonacci number.
		int result;
		switch (n) {
		case 0:
		case 1:
			result = n;
			break;
		default:
			result = fib(n - 1) + fib(n - 2);
			break;
		}
		// Return the result.
		fibPhase.stop();
		return result;
	}

	public static void main(String[] args) {
		// Start ppamltracer.
		Tracer tracer = new Tracer("/tmp/simple_report");

		// Run the app.
		(new Simple()).go(tracer);

		// Finalize ppamltracer and exit.
		tracer.close();
	}

}