summaryrefslogtreecommitdiff
path: root/benchmarks/cmd/profile_example/main.go
blob: 297254a0cbef50168bf9cadd3a85a7d9c3599302 (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
package main

import (
	"fmt"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"time"
)

// Example of using the profiling framework to find performance bottlenecks
func main() {
	fmt.Println("DTail Profiling Example")
	fmt.Println("======================")
	fmt.Println()

	// Create test data
	testFile := createTestData()
	defer os.Remove(testFile)

	// Profile dcat
	fmt.Println("1. Profiling dcat...")
	profileDCat(testFile)

	// Profile dgrep
	fmt.Println("\n2. Profiling dgrep...")
	profileDGrep(testFile)

	// Profile dmap
	csvFile := createCSVData()
	defer os.Remove(csvFile)
	fmt.Println("\n3. Profiling dmap...")
	profileDMap(csvFile)

	// Analyze results
	fmt.Println("\n4. Analyzing profiles...")
	analyzeProfiles()
}

func createTestData() string {
	filename := "test_data.log"
	f, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	// Generate 100MB of log data
	for i := 0; i < 1000000; i++ {
		timestamp := time.Now().Format("2006-01-02 15:04:05.000")
		level := []string{"INFO", "WARN", "ERROR", "DEBUG"}[i%4]
		fmt.Fprintf(f, "[%s] %s - Processing request %d from user%d\n", 
			timestamp, level, i, i%1000)
	}

	return filename
}

func createCSVData() string {
	filename := "test_data.csv"
	f, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	// Header
	fmt.Fprintln(f, "timestamp,user,action,duration,status")

	// Generate data
	for i := 0; i < 100000; i++ {
		timestamp := time.Now().Add(time.Duration(i) * time.Second).Format("2006-01-02 15:04:05")
		user := fmt.Sprintf("user%d", i%100)
		action := []string{"login", "query", "update", "logout"}[i%4]
		duration := 100 + i%900
		status := []string{"success", "failure"}[i%2]
		
		fmt.Fprintf(f, "%s,%s,%s,%d,%s\n", timestamp, user, action, duration, status)
	}

	return filename
}

func profileDCat(testFile string) {
	// Run dcat with profiling
	cmd := exec.Command("../dcat", 
		"-profile",
		"-profiledir", "profiles",
		"-plain",
		"-cfg", "none",
		testFile)

	start := time.Now()
	output, err := cmd.CombinedOutput()
	duration := time.Since(start)

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		fmt.Printf("Output: %s\n", output)
		return
	}

	fmt.Printf("  Completed in %v\n", duration)
	
	// Find generated profiles
	profiles, _ := filepath.Glob("profiles/dcat_*.prof")
	for _, p := range profiles {
		info, _ := os.Stat(p)
		fmt.Printf("  Generated: %s (%d KB)\n", filepath.Base(p), info.Size()/1024)
	}
}

func profileDGrep(testFile string) {
	// Run dgrep with profiling
	cmd := exec.Command("../dgrep",
		"-profile",
		"-profiledir", "profiles",
		"-plain",
		"-cfg", "none",
		"-regex", "ERROR|WARN",
		"-before", "2",
		"-after", "2",
		testFile)

	start := time.Now()
	output, err := cmd.CombinedOutput()
	duration := time.Since(start)

	if err != nil {
		fmt.Printf("Error: %v\n", err)
		fmt.Printf("Output: %s\n", output)
		return
	}

	fmt.Printf("  Completed in %v\n", duration)
	
	// Count matches
	matches := strings.Count(string(output), "ERROR") + strings.Count(string(output), "WARN")
	fmt.Printf("  Found %d matches\n", matches)
}

func profileDMap(csvFile string) {
	// Get absolute path for the CSV file
	absPath, err := filepath.Abs(csvFile)
	if err != nil {
		fmt.Printf("Error getting absolute path: %v\n", err)
		return
	}
	
	// Run dmap with profiling - correct syntax with -files flag
	queries := []string{
		"select count(*)",
		"select user, count(*) group by user",
		"select action, avg(duration), max(duration) group by action",
	}

	for i, query := range queries {
		fmt.Printf("  Query %d: %s\n", i+1, query)
		
		cmd := exec.Command("../dmap",
			"-profile",
			"-profiledir", "profiles",
			"-plain",
			"-cfg", "none",
			"-files", absPath,
			"-query", query)

		start := time.Now()
		output, err := cmd.CombinedOutput()
		duration := time.Since(start)

		if err != nil {
			fmt.Printf("    Error: %v\n", err)
			fmt.Printf("    Output: %s\n", output)
			continue
		}

		fmt.Printf("    Completed in %v\n", duration)
	}
}

func truncateQuery(query string) string {
	if len(query) > 50 {
		return query[:47] + "..."
	}
	return query
}

func analyzeProfiles() {
	// Find latest CPU profiles
	cpuProfiles, _ := filepath.Glob("profiles/*_cpu_*.prof")
	if len(cpuProfiles) == 0 {
		fmt.Println("No CPU profiles found")
		return
	}

	// Analyze each tool's CPU profile
	tools := []string{"dcat", "dgrep", "dmap"}
	for _, tool := range tools {
		var latestProfile string
		var latestTime time.Time

		// Find latest profile for this tool
		for _, profile := range cpuProfiles {
			if strings.Contains(profile, tool+"_cpu_") {
				info, err := os.Stat(profile)
				if err == nil && info.ModTime().After(latestTime) {
					latestProfile = profile
					latestTime = info.ModTime()
				}
			}
		}

		if latestProfile == "" {
			continue
		}

		fmt.Printf("\nAnalyzing %s CPU profile:\n", tool)
		
		// Run dtail-tools profile analyze
		cmd := exec.Command("../dtail-tools",
			"profile", "-mode", "analyze",
			latestProfile)
		
		output, err := cmd.CombinedOutput()
		if err != nil {
			fmt.Printf("  Error analyzing: %v\n", err)
			continue
		}

		// Extract and display key information
		lines := strings.Split(string(output), "\n")
		inTable := false
		for _, line := range lines {
			if strings.Contains(line, "Function") && strings.Contains(line, "Flat") {
				inTable = true
			}
			if inTable && (strings.Contains(line, "%") || strings.Contains(line, "---")) {
				fmt.Printf("  %s\n", line)
			}
			if inTable && line == "" {
				break
			}
		}
		
		// Suggest optimizations based on findings
		suggestOptimizations(tool, string(output))
	}
}

func suggestOptimizations(tool string, analysis string) {
	fmt.Printf("\n  Optimization suggestions for %s:\n", tool)
	
	// Common patterns to look for
	suggestions := []struct {
		pattern string
		suggestion string
	}{
		{"regexp.Compile", "  - Pre-compile regex patterns instead of compiling in loops"},
		{"strings.Join", "  - Use strings.Builder for string concatenation"},
		{"runtime.mallocgc", "  - High allocation rate; consider object pooling"},
		{"syscall", "  - I/O bottleneck; consider buffering or async I/O"},
		{"runtime.gcBgMarkWorker", "  - High GC pressure; reduce allocations"},
	}
	
	foundAny := false
	for _, s := range suggestions {
		if strings.Contains(analysis, s.pattern) {
			fmt.Println(s.suggestion)
			foundAny = true
		}
	}
	
	if !foundAny {
		fmt.Println("  - Profile looks good; no obvious bottlenecks found")
	}
}

// Helper function to demonstrate how to use profiling in tests
func ExampleBenchmarkWithProfiling() {
	// This would typically be in a _test.go file
	fmt.Print(`
Example benchmark with profiling:

func BenchmarkDCatLargeFile(b *testing.B) {
    // Enable profiling for this specific benchmark
    if *cpuprofile != "" {
        f, _ := os.Create(*cpuprofile)
        pprof.StartCPUProfile(f)
        defer pprof.StopCPUProfile()
    }
    
    // Generate test file
    testFile := generateLargeFile(b)
    defer os.Remove(testFile)
    
    b.ResetTimer()
    
    for i := 0; i < b.N; i++ {
        cmd := exec.Command("./dcat", "-plain", testFile)
        cmd.Run()
    }
    
    if *memprofile != "" {
        f, _ := os.Create(*memprofile)
        runtime.GC()
        pprof.WriteHeapProfile(f)
        f.Close()
    }
}

Run with: go test -bench=BenchmarkDCatLargeFile -cpuprofile=cpu.prof -memprofile=mem.prof
`)
}