Skip to content

Commit

Permalink
Define HAVE_TIMERFD on Linux system, for efficient MicroTimer. (#33)
Browse files Browse the repository at this point in the history
Compile the C++ driver with `-DHAVE_TIMERFD`.

### Motivation:

Performance profiling of a service using `swift-cassandra-client` showed
that large amount of time was spent in managing timer list (maintained
as a heap) deep in the Cassandra DataStax C++ driver. Some investigation
later showed that the key blob of code responsible
[here](https://github.com/datastax/cpp-driver/blob/90df2c9ca1aa184a746445698533c71f7f34a2e1/src/micro_timer.cpp#L139-L149):

```
void MicroTimer::on_timeout(Timer* timer) {
  uint64_t now = uv_hrtime();
  if (now >= timeout_ns_) {
    // The goal timeout was reached, trigger the callback.
    callback_(this);
  } else {
    // There's still a sub-millisecond part to wait for so spin the loop until
    // the timeout is reached.
    timer_.start(timer_.loop(), 0, bind_callback(&MicroTimer::on_timeout, this));
  }
}
```

This effectively degrades to a spin-loop, in case we fall through to the
`else` part of the `if`. And we see that in profiling traces. I saw a
case where that was responsible for ~50% of CPU (might be particularly
bad case).

Fortunately, there is an alternative timing implementation. One that is
guarded by `define HAVE_TIMERFD`.

### Modifications:

* define `HAVE_TIMERFD` when built on linux

### Result:

* CPU usage reduces significantly once `HAVE_TIMERFD` is applied
  • Loading branch information
gmilos authored Oct 11, 2024
1 parent 4c395e6 commit fa3870e
Showing 1 changed file with 1 addition and 1 deletion.
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ let package = Package(
.package(url: "https://github.com/apple/swift-nio-ssl", .upToNextMajor(from: "2.21.0")),
.package(url: "https://github.com/apple/swift-atomics", from: "1.0.2"),
.package(url: "https://github.com/apple/swift-log", .upToNextMajor(from: "1.0.0")),
.package(url: "https://github.com/apple/swift-docc-plugin", from: "1.0.0"),
],
targets: [
.target(
Expand Down Expand Up @@ -139,6 +138,7 @@ let package = Package(
],
publicHeadersPath: "./datastax-cpp-driver/include",
cxxSettings: [
.define("HAVE_TIMERFD", .when(platforms: [.linux])), // this is available on all modern Linux systems, and is needed for efficient MicroTimer implementation. Otherwise busy waits are used.
.headerSearchPath("./custom/include"),
.headerSearchPath("./extras"),
.headerSearchPath("./datastax-cpp-driver/src"),
Expand Down

0 comments on commit fa3870e

Please sign in to comment.