CPU profiling of Swift on server.


  • Package.swift

.package(url: "", from: "0.1.0"),


    dependencies: [


gperftoolsSwift is very thin wrapper of gperftools. To start and stop profiling, call Profiler.start and Profiler.stop static function.

import gperftoolsSwift

let file = NSTemporaryDirectory() + "a.profile"
Profiler.start(fname: file)
// do something

A report file is written to <tmp>/a.profile .

If you are using Vapor web framework, you can add utility endpoint like below.

let profilePath = NSTemporaryDirectory() + "a.profile"

app.get("profile") { (req) -> EventLoopFuture<Response> in
    let waitSecond = min((try? req.query.get(TimeInterval.self, at: "s")) ?? 30, 120)
    Profiler.start(fname: profilePath)

    let promise = req.eventLoop.makePromise(of: Response.self) .now() + waitSecond) {
        let res = req.fileio.streamFile(at: profilePath)
    return promise.futureResult

app.get("binary") { (req) -> Response in
    return req.fileio.streamFile(at: ProcessInfo.processInfo.arguments[0])

To start profiling and get the report, call /profile from another terminal.

wget http://localhost:3000/profile?s=60

/binary is also useful to have for later visualization.


pprof is useful to visualize. Install it via golang.

go install[email protected]

(maybe you also need to install graphviz. brew install graphviz. )

To visualize the profile results, use the following command with the executable binary.

pprof -http=":" <executable binary file> <report file>

pprof has many options to visualize reports. see doc.

Frame Graph


View Github