@peccul is peccu

(love peccu '(emacs lisp cat outdoor bicycle mac linux coffee))

macの辞書を引くコマンドをswiftで書くと速かった

macの辞書をターミナルで引ければ楽で速いかなと思い調べたが、Dictionary.appが起動するものとPythonスクリプトしか見当たらなかった。 しかもPythonスクリプトはちょっともたつく。

中身はObjective-Cバインディングを使っているようなので、Swiftで書いてみたらバイナリも生成できるし速かった。という話。

結果

for i in d.py define.py dict.py dict.swift dict
do
  time ./$i window >/dev/null
done
./$i window > /dev/null  0.83s user 0.23s system 83% cpu 1.265 total
./$i window > /dev/null  0.77s user 0.14s system 90% cpu 1.011 total
./$i window > /dev/null  0.74s user 0.14s system 91% cpu 0.965 total
./$i window > /dev/null  0.46s user 1.98s system 74% cpu 3.267 total
./$i window > /dev/null  0.08s user 0.13s system 71% cpu 0.300 total

Pythonスクリプトはリッチな出力があるが、そこまでは求めていないので。

中身

#!/usr/bin/swift
// you can compile into binary by `swiftc dict.swift`
import Foundation

if (CommandLine.argc < 2) {
    print("Usage: dictionary word")
}else{
    let argument = CommandLine.arguments[1]
    let result = DCSCopyTextDefinition(nil, argument as CFString, CFRangeMake(0, argument.count))?.takeRetainedValue() as String?
    print(result ?? "")
}

参考