summaryrefslogtreecommitdiff
path: root/benchmarks/benchmark_results.go
blob: b9319e0be3209427731545dd243835689786fc32 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
package benchmarks

import (
	"encoding/csv"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"
)

// ResultLogger handles benchmark result logging
type ResultLogger struct {
	results []BenchmarkResult
}

// NewResultLogger creates a new result logger
func NewResultLogger() *ResultLogger {
	return &ResultLogger{
		results: make([]BenchmarkResult, 0),
	}
}

// AddResult adds a benchmark result to the logger
func (rl *ResultLogger) AddResult(result BenchmarkResult) {
	result.GitCommit = GetGitCommit()
	result.GoVersion = GetGoVersion()
	rl.results = append(rl.results, result)
}

// WriteJSON writes results to a JSON file
func (rl *ResultLogger) WriteJSON(filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()
	
	encoder := json.NewEncoder(file)
	encoder.SetIndent("", "  ")
	return encoder.Encode(rl.results)
}

// WriteCSV writes results to a CSV file
func (rl *ResultLogger) WriteCSV(filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()
	
	writer := csv.NewWriter(file)
	defer writer.Flush()
	
	// Write header
	header := []string{
		"Timestamp",
		"Tool",
		"Operation",
		"FileSize",
		"Duration",
		"Throughput_MB_sec",
		"Lines_per_sec",
		"Memory_MB",
		"ExitCode",
		"GitCommit",
		"GoVersion",
		"Error",
	}
	if err := writer.Write(header); err != nil {
		return err
	}
	
	// Write data
	for _, result := range rl.results {
		record := []string{
			result.Timestamp.Format(time.RFC3339),
			result.Tool,
			result.Operation,
			fmt.Sprintf("%d", result.FileSize),
			result.Duration.String(),
			fmt.Sprintf("%.2f", result.Throughput),
			fmt.Sprintf("%.2f", result.LinesPerSec),
			fmt.Sprintf("%.2f", float64(result.MemoryUsage)/(1024*1024)),
			fmt.Sprintf("%d", result.ExitCode),
			result.GitCommit,
			result.GoVersion,
			fmt.Sprintf("%v", result.Error),
		}
		if err := writer.Write(record); err != nil {
			return err
		}
	}
	
	return nil
}

// WriteMarkdown writes a human-readable markdown report
func (rl *ResultLogger) WriteMarkdown(filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()
	
	fmt.Fprintf(file, "# DTail Benchmark Results\n\n")
	fmt.Fprintf(file, "**Date**: %s\n", time.Now().Format("2006-01-02 15:04:05"))
	fmt.Fprintf(file, "**Git Commit**: %s\n", GetGitCommit())
	fmt.Fprintf(file, "**Go Version**: %s\n\n", GetGoVersion())
	
	// Group results by tool
	byTool := make(map[string][]BenchmarkResult)
	for _, result := range rl.results {
		byTool[result.Tool] = append(byTool[result.Tool], result)
	}
	
	// Sort tools for consistent output
	var tools []string
	for tool := range byTool {
		tools = append(tools, tool)
	}
	sort.Strings(tools)
	
	// Write results for each tool
	for _, tool := range tools {
		fmt.Fprintf(file, "## %s\n\n", strings.ToUpper(tool))
		
		// Create table
		fmt.Fprintln(file, "| Operation | File Size | Duration | Throughput (MB/s) | Lines/sec |")
		fmt.Fprintln(file, "|-----------|-----------|----------|-------------------|-----------|")
		
		// Sort results by operation name
		results := byTool[tool]
		sort.Slice(results, func(i, j int) bool {
			return results[i].Operation < results[j].Operation
		})
		
		for _, result := range results {
			fmt.Fprintf(file, "| %s | %s | %v | %.2f | %.0f |\n",
				result.Operation,
				formatFileSize(result.FileSize),
				result.Duration.Round(time.Millisecond),
				result.Throughput,
				result.LinesPerSec,
			)
		}
		
		fmt.Fprintln(file, "")
	}
	
	return nil
}

// formatFileSize formats bytes into human-readable size
func formatFileSize(bytes int64) string {
	const (
		KB = 1024
		MB = KB * 1024
		GB = MB * 1024
	)
	
	switch {
	case bytes >= GB:
		return fmt.Sprintf("%.1f GB", float64(bytes)/GB)
	case bytes >= MB:
		return fmt.Sprintf("%.1f MB", float64(bytes)/MB)
	case bytes >= KB:
		return fmt.Sprintf("%.1f KB", float64(bytes)/KB)
	default:
		return fmt.Sprintf("%d B", bytes)
	}
}

// ComparisonReport represents a performance comparison between two runs
type ComparisonReport struct {
	Improvements []ComparisonEntry
	Regressions  []ComparisonEntry
	Unchanged    []ComparisonEntry
}

// ComparisonEntry represents a single comparison result
type ComparisonEntry struct {
	Tool         string
	Operation    string
	BaselineDur  time.Duration
	CurrentDur   time.Duration
	ChangePercent float64
}

// CompareResults compares baseline results with current results
func CompareResults(baseline, current []BenchmarkResult) ComparisonReport {
	// Create maps for easy lookup
	baselineMap := make(map[string]BenchmarkResult)
	for _, result := range baseline {
		key := fmt.Sprintf("%s:%s", result.Tool, result.Operation)
		baselineMap[key] = result
	}
	
	currentMap := make(map[string]BenchmarkResult)
	for _, result := range current {
		key := fmt.Sprintf("%s:%s", result.Tool, result.Operation)
		currentMap[key] = result
	}
	
	report := ComparisonReport{
		Improvements: []ComparisonEntry{},
		Regressions:  []ComparisonEntry{},
		Unchanged:    []ComparisonEntry{},
	}
	
	// Compare each current result with baseline
	for key, currentResult := range currentMap {
		baselineResult, exists := baselineMap[key]
		if !exists {
			continue // Skip new benchmarks
		}
		
		// Calculate percentage change
		changePercent := ((float64(currentResult.Duration) - float64(baselineResult.Duration)) / float64(baselineResult.Duration)) * 100
		
		entry := ComparisonEntry{
			Tool:          currentResult.Tool,
			Operation:     currentResult.Operation,
			BaselineDur:   baselineResult.Duration,
			CurrentDur:    currentResult.Duration,
			ChangePercent: changePercent,
		}
		
		// Categorize based on change threshold (10%)
		switch {
		case changePercent < -10:
			report.Improvements = append(report.Improvements, entry)
		case changePercent > 10:
			report.Regressions = append(report.Regressions, entry)
		default:
			report.Unchanged = append(report.Unchanged, entry)
		}
	}
	
	// Sort by change percentage
	sort.Slice(report.Improvements, func(i, j int) bool {
		return report.Improvements[i].ChangePercent < report.Improvements[j].ChangePercent
	})
	sort.Slice(report.Regressions, func(i, j int) bool {
		return report.Regressions[i].ChangePercent > report.Regressions[j].ChangePercent
	})
	
	return report
}

// WriteComparisonReport writes a comparison report to a file
func WriteComparisonReport(report ComparisonReport, filename string) error {
	file, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer file.Close()
	
	fmt.Fprintln(file, "# Performance Comparison Report")
	fmt.Fprintln(file, "")
	
	// Write regressions
	if len(report.Regressions) > 0 {
		fmt.Fprintln(file, "## ⚠️ Performance Regressions")
		fmt.Fprintln(file, "")
		fmt.Fprintln(file, "| Tool | Operation | Baseline | Current | Change |")
		fmt.Fprintln(file, "|------|-----------|----------|---------|--------|")
		
		for _, entry := range report.Regressions {
			fmt.Fprintf(file, "| %s | %s | %v | %v | +%.1f%% |\n",
				entry.Tool,
				entry.Operation,
				entry.BaselineDur.Round(time.Millisecond),
				entry.CurrentDur.Round(time.Millisecond),
				entry.ChangePercent,
			)
		}
		fmt.Fprintln(file, "")
	}
	
	// Write improvements
	if len(report.Improvements) > 0 {
		fmt.Fprintln(file, "## ✅ Performance Improvements")
		fmt.Fprintln(file, "")
		fmt.Fprintln(file, "| Tool | Operation | Baseline | Current | Change |")
		fmt.Fprintln(file, "|------|-----------|----------|---------|--------|")
		
		for _, entry := range report.Improvements {
			fmt.Fprintf(file, "| %s | %s | %v | %v | %.1f%% |\n",
				entry.Tool,
				entry.Operation,
				entry.BaselineDur.Round(time.Millisecond),
				entry.CurrentDur.Round(time.Millisecond),
				entry.ChangePercent,
			)
		}
		fmt.Fprintln(file, "")
	}
	
	// Summary
	fmt.Fprintln(file, "## Summary")
	fmt.Fprintln(file, "")
	fmt.Fprintf(file, "- Regressions: %d\n", len(report.Regressions))
	fmt.Fprintf(file, "- Improvements: %d\n", len(report.Improvements))
	fmt.Fprintf(file, "- Unchanged: %d\n", len(report.Unchanged))
	
	return nil
}

// SaveResults saves benchmark results in multiple formats
func SaveResults(results []BenchmarkResult) error {
	logger := NewResultLogger()
	for _, result := range results {
		logger.AddResult(result)
	}
	
	timestamp := time.Now().Format("20060102_150405")
	baseDir := "benchmark_results"
	
	// Create results directory
	if err := os.MkdirAll(baseDir, 0755); err != nil {
		return err
	}
	
	// Save in different formats
	jsonFile := filepath.Join(baseDir, fmt.Sprintf("results_%s.json", timestamp))
	if err := logger.WriteJSON(jsonFile); err != nil {
		return err
	}
	
	csvFile := filepath.Join(baseDir, fmt.Sprintf("results_%s.csv", timestamp))
	if err := logger.WriteCSV(csvFile); err != nil {
		return err
	}
	
	mdFile := filepath.Join(baseDir, fmt.Sprintf("results_%s.md", timestamp))
	if err := logger.WriteMarkdown(mdFile); err != nil {
		return err
	}
	
	// Also save as latest for easy access
	latestJSON := filepath.Join(baseDir, "latest.json")
	if err := logger.WriteJSON(latestJSON); err != nil {
		return err
	}
	
	return nil
}