summaryrefslogtreecommitdiffstats
path: root/Essentials/src/com/earth2me/essentials/ExecuteTimer.java
blob: f9da468b5a5f7d97ba7a1a020079bbbf088e755d (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
85
86
87
88
89
package com.earth2me.essentials;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;


public class ExecuteTimer
{
	private final transient List<ExecuteRecord> times;
	private final transient DecimalFormat decimalFormat = new DecimalFormat("#0.000", DecimalFormatSymbols.getInstance(Locale.US));


	public ExecuteTimer()
	{
		times = new ArrayList<ExecuteRecord>();
	}

	public void start()
	{
		times.clear();
		mark("start");

	}

	public void mark(final String label)
	{
		if (!times.isEmpty() || "start".equals(label))
		{
			times.add(new ExecuteRecord(label, System.nanoTime()));
		}
	}

	public String end()
	{
		final StringBuilder output = new StringBuilder();
		output.append("execution time: ");
		String mark;
		long time0 = 0;
		long time1 = 0;
		long time2 = 0;
		double duration;

		for (ExecuteRecord pair : times)
		{
			mark = (String)pair.getMark();
			time2 = (Long)pair.getTime();
			if (time1 > 0)
			{
				duration = (time2 - time1)/1000000.0;
				output.append(mark).append(": ").append(decimalFormat.format(duration)).append("ms - ");
			}
			else
			{
				time0 = time2;
			}
			time1 = time2;
		}
		duration = (time1 - time0)/1000000.0;
		output.append("Total: ").append(decimalFormat.format(duration)).append("ms");
		times.clear();
		return output.toString();
	}


	private static class ExecuteRecord
	{
		private final String mark;
		private final long time;

		public ExecuteRecord(final String mark, final long time)
		{
			this.mark = mark;
			this.time = time;
		}

		public String getMark()
		{
			return mark;
		}

		public long getTime()
		{
			return time;
		}
	}
}