@@ -39,6 +39,12 @@ class ClickCoordinator: ObservableObject {
3939 /// Active automation task
4040 private var automationTask : Task < Void , Never > ?
4141
42+ /// High-precision timer for optimized automation timing
43+ private var automationTimer : HighPrecisionTimer ?
44+
45+ /// Performance monitor for resource optimization
46+ private let performanceMonitor = PerformanceMonitor . shared
47+
4248 /// Statistics tracking
4349 private var sessionStartTime : TimeInterval = 0
4450 private var totalClicks : Int = 0
@@ -65,9 +71,13 @@ class ClickCoordinator: ObservableObject {
6571
6672 print ( " ClickCoordinator: Starting automation at \( configuration. location) " )
6773
68- automationTask = Task {
69- await runAutomationLoop ( configuration: configuration)
74+ // Start performance monitoring if not already running
75+ if !performanceMonitor. isMonitoring {
76+ performanceMonitor. startMonitoring ( )
7077 }
78+
79+ // Use high-precision timer for better CPU efficiency
80+ startOptimizedAutomationLoop ( configuration: configuration)
7181 }
7282
7383 /// Stops the current automation session
@@ -82,6 +92,12 @@ class ClickCoordinator: ObservableObject {
8292
8393 isActive = false
8494 isPaused = false // Clear pause state when stopping
95+
96+ // Stop automation timer
97+ automationTimer? . stopTimer ( )
98+ automationTimer = nil
99+
100+ // Cancel any remaining automation task
85101 automationTask? . cancel ( )
86102 automationTask = nil
87103
@@ -100,7 +116,9 @@ class ClickCoordinator: ObservableObject {
100116 isActive = false
101117 isPaused = false
102118
103- // Immediate task cancellation without waiting
119+ // Immediate timer and task cancellation without waiting
120+ automationTimer? . stopTimer ( )
121+ automationTimer = nil
104122 automationTask? . cancel ( )
105123 automationTask = nil
106124
@@ -252,54 +270,81 @@ class ClickCoordinator: ObservableObject {
252270 return errorRecoveryManager. getRecoveryStatistics ( )
253271 }
254272
273+ /// Gets current performance metrics
274+ /// - Returns: Current performance report
275+ func getPerformanceMetrics( ) -> PerformanceReport {
276+ return performanceMonitor. getPerformanceReport ( )
277+ }
278+
279+ /// Gets timing accuracy statistics from the automation timer
280+ /// - Returns: Timing accuracy statistics
281+ func getTimingAccuracy( ) -> TimingAccuracyStats ? {
282+ return automationTimer? . getTimingAccuracy ( )
283+ }
284+
285+ /// Optimizes performance based on current metrics
286+ func optimizePerformance( ) {
287+ performanceMonitor. optimizeMemoryUsage ( )
288+
289+ // Reset timing statistics for fresh measurement
290+ automationTimer? . resetTimingStats ( )
291+
292+ print ( " [ClickCoordinator] Performance optimization completed " )
293+ }
294+
255295 // MARK: - Private Methods
256296
257- /// Runs the main automation loop
297+ /// Starts optimized automation loop using HighPrecisionTimer for better CPU efficiency
258298 /// - Parameter configuration: Automation configuration
259- private func runAutomationLoop( configuration: AutomationConfiguration ) async {
260- while isActive && !Task. isCancelled {
261- // Skip execution if paused, but continue loop
262- if isPaused {
263- try ? await Task . sleep ( nanoseconds: 50_000_000 ) // 50ms pause check interval
264- continue
265- }
266-
267- let result = await executeAutomationStep ( configuration: configuration)
268-
269- if !result. success {
270- // Handle failed click based on configuration
271- if configuration. stopOnError {
272- await MainActor . run {
273- stopAutomation ( )
274- }
275- break
276- }
277- }
278-
279- // Apply click interval
280- if configuration. clickInterval > 0 {
281- try ? await Task . sleep ( nanoseconds: UInt64 ( configuration. clickInterval * 1_000_000_000 ) )
282- }
283-
284- // Check for maximum clicks limit
285- if let maxClicks = configuration. maxClicks, totalClicks >= maxClicks {
286- await MainActor . run {
287- stopAutomation ( )
288- }
289- break
299+ private func startOptimizedAutomationLoop( configuration: AutomationConfiguration ) {
300+ guard configuration. clickInterval > 0 else {
301+ print ( " ClickCoordinator: Invalid click interval: \( configuration. clickInterval) " )
302+ return
303+ }
304+
305+ // Create high-precision timer for automation
306+ automationTimer = HighPrecisionTimer ( )
307+
308+ // Start timer-based automation loop
309+ automationTimer? . startRepeatingTimer ( interval: configuration. clickInterval) { [ weak self] in
310+ Task { @MainActor in
311+ await self ? . performOptimizedAutomationStep ( configuration: configuration)
290312 }
291-
292- // Check for maximum duration limit
293- if let maxDuration = configuration. maxDuration {
294- let elapsedTime = CFAbsoluteTimeGetCurrent ( ) - sessionStartTime
295- if elapsedTime >= maxDuration {
296- await MainActor . run {
297- stopAutomation ( )
298- }
299- break
300- }
313+ }
314+
315+ print ( " ClickCoordinator: Started optimized automation loop with \( configuration. clickInterval * 1000 ) ms interval " )
316+ }
317+
318+ /// Performs a single optimized automation step with minimal overhead
319+ /// - Parameter configuration: Automation configuration
320+ private func performOptimizedAutomationStep( configuration: AutomationConfiguration ) async {
321+ // Quick exit checks for maximum efficiency
322+ guard isActive else { return }
323+
324+ // Skip execution if paused but keep timer running
325+ guard !isPaused else { return }
326+
327+ // Check limits before execution for efficiency
328+ if let maxClicks = configuration. maxClicks, totalClicks >= maxClicks {
329+ stopAutomation ( )
330+ return
331+ }
332+
333+ if let maxDuration = configuration. maxDuration {
334+ let elapsedTime = CFAbsoluteTimeGetCurrent ( ) - sessionStartTime
335+ if elapsedTime >= maxDuration {
336+ stopAutomation ( )
337+ return
301338 }
302339 }
340+
341+ // Execute click with minimal overhead
342+ let result = await executeAutomationStep ( configuration: configuration)
343+
344+ // Handle failed click with minimal processing
345+ if !result. success && configuration. stopOnError {
346+ stopAutomation ( )
347+ }
303348 }
304349
305350 /// Executes a single automation step with error recovery
0 commit comments