admin管理员组

文章数量:1196756

The goal of our Swift code is to move the currently focused window 1 pixel to the right. We are on macOS.

This is our Swift code:

let startTime = Date()

import Cocoa
import ApplicationServices

// Get the frontmost application
if let app = NSWorkspace.shared.frontmostApplication {
    let appPID = app.processIdentifier
    let axApp = AXUIElementCreateApplication(appPID)
    
    // Get the focused window of the application
    var window: CFTypeRef?
    if AXUIElementCopyAttributeValue(axApp, kAXFocusedWindowAttribute as CFString, &window) == .success {
        let axWindow = window as! AXUIElement  // Direct cast to AXUIElement
        
        // Get the current position of the window
        var position: CFTypeRef?
        if AXUIElementCopyAttributeValue(axWindow, kAXPositionAttribute as CFString, &position) == .success {
            let axValue = position as! AXValue  // Direct cast to AXValue
            var currentPos = CGPoint()
            if AXValueGetValue(axValue, .cgPoint, &currentPos) {
                // Move the window by 1 point to the right
                var newPos = CGPoint(x: currentPos.x + 1, y: currentPos.y)
                if let newPosValue = AXValueCreate(.cgPoint, &newPos) {
                    AXUIElementSetAttributeValue(axWindow, kAXPositionAttribute as CFString, newPosValue as CFTypeRef)
                }
            }
        }
    }
}

let elapsedTime = Date().timeIntervalSince(startTime)
print("Elapsed time: \(elapsedTime) seconds")

This is our terminal:

a@as-MacBook-Pro mo % swift index.swift                             
Elapsed time: 0.02612602710723877 seconds
a@as-MacBook-Pro mo % swiftc -O index.swift -o move_window          
a@as-MacBook-Pro mo % ./move_window                                 
Elapsed time: 0.043260931968688965 seconds

We tried running the Swift code with the Swift interpreter using the swift index.swift command, as well as compiling and running the Swift code with these two commands swiftc -O index.swift -o move_window ./move_window.

We expected the "elapsed time" to be lower on the compiled code.

The result was that the "elapsed time" was higher on the compiled code.

本文标签: macosWhy does our compiled Swift code seem to run slower than our interpreted Swift codeStack Overflow