mirror of
https://github.com/apple/swift-nio
synced 2026-11-23 04:34:23 +00:00
Introduce parallel removal of items, instead of only doing a sequential removal (and discovery) one-by-one ### Motivation: #2933 mentioned this function call appears to be slow. If we attempt to delete a directory with lots of subdirectories, we end up discovering each subdirectory one by one on a single thread. ### Modifications: This PR refactors the logic to remove items. Instead of sequentially discovering and deleting items one by one, we traverse all directories up to a maximum concurrency, and issue file deletions in parallel within each directory. ### Result: The new concurrent implementation was measured to be ~1.4x faster than `FileManager`, ~1.5x faster than `rm -rf` and ~3x faster than the current sequential implementation on `main`. This new concurrent implementation does use the most CPU out of all the other approaches. Results are broken down into two sections. We delete a copy of the `swift-nio` repository, where the `.build/` folder has grown to a large size, providing lots of additional files and subdirectories. We produce a single CLI using `--configration=release` that can switch between using the `.sequential` mode (what is currently available on the `main` branch), `.parallel` (the new concurrent implementation in this PR) and `filemanager` (uses `Foundation.FileManager` as a comparison). Resolves https://github.com/apple/swift-nio/issues/2933 #### Normal size **Description:** The `swift-nio` library as found when building the CLI used for benchmarking. **Benchmark run with:** 3579 directories, 11657 files ``` $ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio" Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio Time (mean ± σ): 2.712 s ± 0.053 s [User: 0.526 s, System: 8.632 s] Range (min … max): 2.625 s … 2.781 s 10 runs Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio Time (mean ± σ): 896.7 ms ± 25.6 ms [User: 302.9 ms, System: 5313.5 ms] Range (min … max): 853.2 ms … 942.1 ms 10 runs Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio Time (mean ± σ): 1.337 s ± 0.076 s [User: 0.022 s, System: 1.253 s] Range (min … max): 1.252 s … 1.508 s 10 runs Benchmark 4: rm -rf /tmp/swift-nio Time (mean ± σ): 1.483 s ± 0.037 s [User: 0.015 s, System: 1.416 s] Range (min … max): 1.413 s … 1.541 s 10 runs Summary .build/release/NIOTestCLI --parallel /tmp/swift-nio ran 1.49 ± 0.10 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio 1.65 ± 0.06 times faster than rm -rf /tmp/swift-nio 3.02 ± 0.10 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio ``` #### Large size **Description:** The `swift-nio` library as found after re-running the `.github` workflow many times locally. I'm unable to reproduce this directory size, but have benchmarked against it. **Benchmark run with:** 15260 directories, 46842 files ``` $ hyperfine --runs 10 --warmup 2 --prepare "rm -rf /tmp/swift-nio && cp -r $(pwd) /tmp/swift-nio" ".build/release/NIOTestCLI --sequential /tmp/swift-nio" ".build/release/NIOTestCLI --parallel /tmp/swift-nio" ".build/release/NIOTestCLI --filemanager /tmp/swift-nio" "rm -rf /tmp/swift-nio" Benchmark 1: .build/release/NIOTestCLI --sequential /tmp/swift-nio Time (mean ± σ): 12.082 s ± 0.354 s [User: 2.180 s, System: 41.547 s] Range (min … max): 11.717 s … 12.923 s 10 runs Benchmark 2: .build/release/NIOTestCLI --parallel /tmp/swift-nio Time (mean ± σ): 4.770 s ± 0.102 s [User: 1.357 s, System: 25.785 s] Range (min … max): 4.570 s … 4.883 s 10 runs Benchmark 3: .build/release/NIOTestCLI --filemanager /tmp/swift-nio Time (mean ± σ): 6.503 s ± 0.115 s [User: 0.081 s, System: 5.427 s] Range (min … max): 6.262 s … 6.687 s 10 runs Benchmark 4: rm -rf /tmp/swift-nio Time (mean ± σ): 7.056 s ± 0.246 s [User: 0.064 s, System: 6.119 s] Range (min … max): 6.435 s … 7.233 s 10 runs Summary .build/release/NIOTestCLI --parallel /tmp/swift-nio ran 1.36 ± 0.04 times faster than .build/release/NIOTestCLI --filemanager /tmp/swift-nio 1.48 ± 0.06 times faster than rm -rf /tmp/swift-nio 2.53 ± 0.09 times faster than .build/release/NIOTestCLI --sequential /tmp/swift-nio ``` --------- Co-authored-by: George Barnett <gbarnett@apple.com>
185 lines
8.3 KiB
Swift
185 lines
8.3 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the SwiftNIO open source project
|
|
//
|
|
// Copyright (c) 2024 Apple Inc. and the SwiftNIO project authors
|
|
// Licensed under Apache License v2.0
|
|
//
|
|
// See LICENSE.txt for license information
|
|
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
|
|
//
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
//
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
/// How many file descriptors to open when performing I/O operations.
|
|
enum IOStrategy: Hashable, Sendable {
|
|
// platformDefault is reified into one of the concrete options below:
|
|
case sequential
|
|
case parallel(_ maxDescriptors: Int)
|
|
|
|
// These selections are relatively arbitrary but the rationale is as follows:
|
|
//
|
|
// - Never exceed the default OS limits even if 4 such operations were happening at once.
|
|
// - Sufficient to enable significant speed up from parallelism
|
|
// - Not wasting effort by pushing contention to the underlying storage device. Further we
|
|
// assume an SSD or similar underlying storage tech. Users on spinning rust need to account
|
|
// for that themselves anyway.
|
|
//
|
|
// That said, empirical testing for this has not been performed, suggestions welcome.
|
|
//
|
|
// Note: The directory scan is modelled after a copy strategy needing two handles: during the
|
|
// creation of the destination directory we hold the handle while copying attributes. A much
|
|
// more complex internal state machine could allow doing two of these if desired. This may not
|
|
// result in a faster copy though so things are left simple.
|
|
internal static func determinePlatformDefault() -> Self {
|
|
#if os(macOS) || os(Linux) || os(Windows)
|
|
// Eight file descriptors allow for four concurrent file copies/directory scans. Avoiding
|
|
// storage system contention is of utmost importance.
|
|
//
|
|
// Testing was performed on an SSD, while copying objects (a dense directory of small files
|
|
// and subdirectories of similar shape) to the same volume, totalling 12GB. Results showed
|
|
// improvements in elapsed time for (expected) increases in CPU time up to parallel(8).
|
|
// Beyond this, the increases in CPU led to only moderate gains.
|
|
//
|
|
// Anyone tuning this is encouraged to cover worst case scenarios.
|
|
return .parallel(8)
|
|
#elseif os(iOS) || os(tvOS) || os(watchOS) || os(Android)
|
|
// Reduced maximum descriptors in embedded world. This is chosen based on biasing towards
|
|
// safety, not empirical testing.
|
|
return .parallel(4)
|
|
#else
|
|
// Safety first. If we do not know what system we run on, we keep it simple.
|
|
return .sequential
|
|
#endif
|
|
}
|
|
}
|
|
|
|
/// How to perform copies. Currently only relevant to directory level copies when using
|
|
/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` or other
|
|
/// overloads that use the default behaviour.
|
|
public struct CopyStrategy: Hashable, Sendable {
|
|
internal let wrapped: IOStrategy
|
|
private init(_ strategy: IOStrategy) {
|
|
switch strategy {
|
|
case .sequential:
|
|
self.wrapped = .sequential
|
|
case let .parallel(maxDescriptors):
|
|
self.wrapped = .parallel(maxDescriptors)
|
|
}
|
|
}
|
|
|
|
// A copy fundamentally can't work without two descriptors unless you copy everything into
|
|
// memory which is infeasible/inefficient for large copies.
|
|
private static let minDescriptorsAllowed = 2
|
|
|
|
/// Operate in whatever manner is deemed a reasonable default for the platform. This will limit
|
|
/// the maximum file descriptors usage based on reasonable defaults.
|
|
///
|
|
/// Current assumptions (which are subject to change):
|
|
/// - Only one copy operation would be performed at once
|
|
/// - The copy operation is not intended to be the primary activity on the device
|
|
public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault())
|
|
|
|
/// The copy is done asynchronously, but only one operation will occur at a time. This is the
|
|
/// only way to guarantee only one callback to the `shouldCopyItem` will happen at a time.
|
|
public static let sequential: Self = Self(.sequential)
|
|
|
|
/// Allow multiple I/O operations to run concurrently, including file copies/directory creation
|
|
/// and scanning.
|
|
///
|
|
/// - Parameter maxDescriptors: a conservative limit on the number of concurrently open file
|
|
/// descriptors involved in the copy. This number must be >= 2 though, if you are using a
|
|
/// value that low you should use ``sequential``
|
|
///
|
|
/// - Throws: ``FileSystemError/Code-swift.struct/invalidArgument`` if `maxDescriptors` is less
|
|
/// than 2.
|
|
///
|
|
public static func parallel(maxDescriptors: Int) throws -> Self {
|
|
guard maxDescriptors >= Self.minDescriptorsAllowed else {
|
|
// 2 is not quite the same as sequential, you could have two concurrent directory
|
|
// listings for example less than 2 and you can't actually do a _copy_ though so it's
|
|
// non-sensical.
|
|
throw FileSystemError(
|
|
code: .invalidArgument,
|
|
message: "Can't do a copy operation without at least 2 file descriptors '\(maxDescriptors)' is illegal",
|
|
cause: nil,
|
|
location: .here()
|
|
)
|
|
}
|
|
return .init(.parallel(maxDescriptors))
|
|
}
|
|
}
|
|
|
|
extension CopyStrategy: CustomStringConvertible {
|
|
public var description: String {
|
|
switch self.wrapped {
|
|
case .sequential:
|
|
return "sequential"
|
|
case let .parallel(maxDescriptors):
|
|
return "parallel with max \(maxDescriptors) descriptors"
|
|
}
|
|
}
|
|
}
|
|
|
|
/// How to perform file deletions. Currently only relevant to directory level deletions when using
|
|
/// ``FileSystemProtocol/removeItem(at:strategy:recursively:)`` or other overloads that use the
|
|
/// default behaviour.
|
|
public struct RemovalStrategy: Hashable, Sendable {
|
|
internal let wrapped: IOStrategy
|
|
private init(_ strategy: IOStrategy) {
|
|
switch strategy {
|
|
case .sequential:
|
|
self.wrapped = .sequential
|
|
case let .parallel(maxDescriptors):
|
|
self.wrapped = .parallel(maxDescriptors)
|
|
}
|
|
}
|
|
|
|
// A deletion requires no file descriptors. We only consume a file descriptor while scanning the
|
|
// contents of a directory, so the minimum is 1.
|
|
private static let minRequiredDescriptors = 1
|
|
|
|
/// Operate in whatever manner is deemed a reasonable default for the platform. This will limit
|
|
/// the maximum file descriptors usage based on reasonable defaults.
|
|
///
|
|
/// Current assumptions (which are subject to change):
|
|
/// - Only one delete operation would be performed at once
|
|
/// - The delete operation is not intended to be the primary activity on the device
|
|
public static let platformDefault: Self = Self(IOStrategy.determinePlatformDefault())
|
|
|
|
/// Traversal of directories and removal of files will be done sequentially without any
|
|
/// parallelization.
|
|
public static let sequential: Self = Self(.sequential)
|
|
|
|
/// Allow for one or more directory scans to run at the same time. Removal of files will happen
|
|
/// on asynchronous tasks in parallel.
|
|
///
|
|
/// Setting `maxDescriptors` to 1, will limit the speed of directory discovery. Deletion of
|
|
/// files within that directory will run in parallel, but discovery of subdirectories will be
|
|
/// limited to one at a time.
|
|
public static func parallel(maxDescriptors: Int) throws -> Self {
|
|
guard maxDescriptors >= Self.minRequiredDescriptors else {
|
|
throw FileSystemError(
|
|
code: .invalidArgument,
|
|
message:
|
|
"Can't do a remove operation without at least one file descriptor '\(maxDescriptors)' is illegal",
|
|
cause: nil,
|
|
location: .here()
|
|
)
|
|
}
|
|
return .init(.parallel(maxDescriptors))
|
|
}
|
|
}
|
|
|
|
extension RemovalStrategy: CustomStringConvertible {
|
|
public var description: String {
|
|
switch self.wrapped {
|
|
case .sequential:
|
|
return "sequential"
|
|
case let .parallel(maxDescriptors):
|
|
return "parallel with max \(maxDescriptors) descriptors"
|
|
}
|
|
}
|
|
}
|