From 7cc32a9a41e348230a4a452b25b7308cae1f3652 Mon Sep 17 00:00:00 2001 From: Cory Benfield Date: Wed, 13 Nov 2019 08:43:10 +0000 Subject: [PATCH] Add HPACK & Huffman benchmarks. (#167) Motivation: Having benchmarks for the HPACK encoder and decoder gives us better insight into their performance. While we have some simple benchmarks in the XCTests, using the NIO performance tester framework will give us more insight into what's happening. While we're here, we can move the Huffman benchmarks out of the unit tests and into the benchmark suite. Modifications: Added encoder, decoder, and huffman benchmarks. Result: Better performance numbers. --- .../NIOHTTP2PerformanceTester/Benchmark.swift | 4 +- .../HPACKHeaderDecodingBenchmark.swift | 55 ++++++++ .../HPACKHeaderEncodingBenchmark.swift | 71 +++++++++++ .../HuffmanDecodingBenchmark.swift | 118 ++++++++++++++++++ .../HuffmanEncodingBenchmark.swift | 77 ++++++++++++ Sources/NIOHTTP2PerformanceTester/main.swift | 12 +- .../HuffmanCodingTests+XCTest.swift | 4 - Tests/NIOHPACKTests/HuffmanCodingTests.swift | 106 ---------------- 8 files changed, 333 insertions(+), 114 deletions(-) create mode 100644 Sources/NIOHTTP2PerformanceTester/HPACKHeaderDecodingBenchmark.swift create mode 100644 Sources/NIOHTTP2PerformanceTester/HPACKHeaderEncodingBenchmark.swift create mode 100644 Sources/NIOHTTP2PerformanceTester/HuffmanDecodingBenchmark.swift create mode 100644 Sources/NIOHTTP2PerformanceTester/HuffmanEncodingBenchmark.swift diff --git a/Sources/NIOHTTP2PerformanceTester/Benchmark.swift b/Sources/NIOHTTP2PerformanceTester/Benchmark.swift index cb9714d..f2128d6 100644 --- a/Sources/NIOHTTP2PerformanceTester/Benchmark.swift +++ b/Sources/NIOHTTP2PerformanceTester/Benchmark.swift @@ -13,14 +13,12 @@ //===----------------------------------------------------------------------===// protocol Benchmark: class { - init() func setUp() throws func tearDown() func run() throws -> Int } -func measureAndPrint(desc: String, benchmark: B.Type) throws { - let bench = B() +func measureAndPrint(desc: String, benchmark bench: B) throws { try bench.setUp() defer { bench.tearDown() diff --git a/Sources/NIOHTTP2PerformanceTester/HPACKHeaderDecodingBenchmark.swift b/Sources/NIOHTTP2PerformanceTester/HPACKHeaderDecodingBenchmark.swift new file mode 100644 index 0000000..37577c9 --- /dev/null +++ b/Sources/NIOHTTP2PerformanceTester/HPACKHeaderDecodingBenchmark.swift @@ -0,0 +1,55 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019 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 +// +//===----------------------------------------------------------------------===// + +import NIO +import NIOHPACK + + +final class HPACKHeaderDecodingBenchmark { + private var headers: ByteBuffer + private let loopCount: Int + private var decoder: HPACKDecoder + + init(headers: HPACKHeaders, loopCount: Int) { + self.headers = headers.encoded + self.loopCount = loopCount + self.decoder = HPACKDecoder(allocator: .init()) + } +} + + +extension HPACKHeaderDecodingBenchmark: Benchmark { + func setUp() throws { } + + func tearDown() { } + + func run() throws -> Int { + for _ in 0.. Int { + for _ in 0.. Int { + for _ in 0..= 1) + + let k = (1 << prefix) - 1 + var initialByte = prefixBits + + if value < k { + // it fits already! + initialByte |= UInt8(truncatingIfNeeded: value) + self.writeInteger(initialByte) + return + } + + // if it won't fit in this byte altogether, fill in all the remaining bits and move + // to the next byte. + initialByte |= UInt8(truncatingIfNeeded: k) + self.writeInteger(initialByte) + + // deduct the initial [prefix] bits from the value, then encode it seven bits at a time into + // the remaining bytes. + var n = value - UInt(k) + while n >= 128 { + let nextByte = (1 << 7) | UInt8(n & 0x7f) + self.writeInteger(nextByte) + n >>= 7 + } + + self.writeInteger(UInt8(n)) + } +} diff --git a/Sources/NIOHTTP2PerformanceTester/HuffmanEncodingBenchmark.swift b/Sources/NIOHTTP2PerformanceTester/HuffmanEncodingBenchmark.swift new file mode 100644 index 0000000..486d1f0 --- /dev/null +++ b/Sources/NIOHTTP2PerformanceTester/HuffmanEncodingBenchmark.swift @@ -0,0 +1,77 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftNIO open source project +// +// Copyright (c) 2019 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 +// +//===----------------------------------------------------------------------===// + +import NIO +import NIOHPACK + + +/// This benchmark is mostly attempting to stress the Huffman Encoding implementation by +/// way of using larger or more complex strings. +final class HuffmanEncodingBenchmark { + private var headers: HPACKHeaders + private let loopCount: Int + private var encoder: HPACKEncoder + private var buffer: ByteBuffer + + init(huffmanString: String, loopCount: Int) { + self.headers = HPACKHeaders() + self.headers.add(name: "f", value: huffmanString, indexing: .neverIndexed) + + self.loopCount = loopCount + self.encoder = HPACKEncoder(allocator: .init()) + self.buffer = ByteBufferAllocator().buffer(capacity: 1024) + } +} + + +extension HuffmanEncodingBenchmark: Benchmark { + func setUp() throws { + // Run a single iteration of the loop. This warms up the encoder and decoder and ensures all the pages are mapped. + try self.loopIteration() + } + + func tearDown() { } + + func run() throws -> Int { + for _ in 0.. Int) rethrows -> Void // MARK: Utilities -try measureAndPrint(desc: "1_conn_10k_reqs", benchmark: Bench1Conn10kRequests.self) +try measureAndPrint(desc: "1_conn_10k_reqs", benchmark: Bench1Conn10kRequests()) +try measureAndPrint(desc: "encode_100k_header_blocks_indexable", benchmark: HPACKHeaderEncodingBenchmark(headers: .indexable, loopCount: 100_000)) +try measureAndPrint(desc: "encode_100k_header_blocks_nonindexable", benchmark: HPACKHeaderEncodingBenchmark(headers: .nonIndexable, loopCount: 100_000)) +try measureAndPrint(desc: "encode_100k_header_blocks_neverIndexed", benchmark: HPACKHeaderEncodingBenchmark(headers: .neverIndexed, loopCount: 100_000)) +try measureAndPrint(desc: "decode_100k_header_blocks_indexable", benchmark: HPACKHeaderDecodingBenchmark(headers: .indexable, loopCount: 100_000)) +try measureAndPrint(desc: "decode_100k_header_blocks_nonindexable", benchmark: HPACKHeaderDecodingBenchmark(headers: .nonIndexable, loopCount: 100_000)) +try measureAndPrint(desc: "decode_100k_header_blocks_neverIndexed", benchmark: HPACKHeaderDecodingBenchmark(headers: .neverIndexed, loopCount: 100_000)) +try measureAndPrint(desc: "huffman_encode_basic", benchmark: HuffmanEncodingBenchmark(huffmanString: .basicHuffmanString, loopCount: 100)) +try measureAndPrint(desc: "huffman_encode_complex", benchmark: HuffmanEncodingBenchmark(huffmanString: .complexHuffmanString, loopCount: 100)) +try measureAndPrint(desc: "huffman_decode_basic", benchmark: HuffmanDecodingBenchmark(huffmanBytes: .basicHuffmanBytes, loopCount: 25)) +try measureAndPrint(desc: "huffman_decode_complex", benchmark: HuffmanDecodingBenchmark(huffmanBytes: .complexHuffmanBytes, loopCount: 10)) diff --git a/Tests/NIOHPACKTests/HuffmanCodingTests+XCTest.swift b/Tests/NIOHPACKTests/HuffmanCodingTests+XCTest.swift index de7e666..0299903 100644 --- a/Tests/NIOHPACKTests/HuffmanCodingTests+XCTest.swift +++ b/Tests/NIOHPACKTests/HuffmanCodingTests+XCTest.swift @@ -28,10 +28,6 @@ extension HuffmanCodingTests { return [ ("testBasicCoding", testBasicCoding), ("testComplexCoding", testComplexCoding), - ("testBasicEncodingPerformance", testBasicEncodingPerformance), - ("testBasicDecodingPerformance", testBasicDecodingPerformance), - ("testComplexEncodingPerformance", testComplexEncodingPerformance), - ("testComplexDecodingPerformance", testComplexDecodingPerformance), ] } } diff --git a/Tests/NIOHPACKTests/HuffmanCodingTests.swift b/Tests/NIOHPACKTests/HuffmanCodingTests.swift index 00b0019..9824a5a 100644 --- a/Tests/NIOHPACKTests/HuffmanCodingTests.swift +++ b/Tests/NIOHPACKTests/HuffmanCodingTests.swift @@ -19,25 +19,8 @@ import Foundation @testable import NIOHPACK class HuffmanCodingTests: XCTestCase { - /// Control timing-sensitive tests from command-line in run-time: - /// ENABLE_TIMING_TESTS=false swift test - /// ENABLED_SANITIZERS=true swift test -fsanitize=thread - /// or during compile time: - /// swift test -fsanitize=thread -DENABLED_SANITIZERS - let timeSensitiveTestEnabled: Bool = { - #if ENABLED_SANITIZERS - return false - #else - let env = ProcessInfo.processInfo.environment - return ((env["ENABLED_SANITIZERS"] ?? "false") == "false") - && ((env["ENABLE_TIMING_TESTS"] ?? "true") == "true") - #endif - }() - var scratchBuffer: ByteBuffer = ByteBufferAllocator().buffer(capacity: 4096) - let fixtureDirURL = URL(fileURLWithPath: #file).deletingLastPathComponent().appendingPathComponent("Fixtures").absoluteURL - // MARK: - Helper Methods func assertEqualContents(_ buffer: ByteBuffer, _ array: [UInt8], file: StaticString = #file, line: UInt = #line) { @@ -103,93 +86,4 @@ class HuffmanCodingTests: XCTestCase { try verifyHuffmanCoding(text2, Array(encoded2Data)) } - - func testBasicEncodingPerformance() { - guard self.timeSensitiveTestEnabled else { return } - - var text = "Hello, world. I am a header value; I have Teh Texts. I am going on for quite a long time because I want to ensure that the encoded data buffer needs to be expanded to test out that code. I'll try some meta-characters too: \r\t\n ought to do it, no?" - while text.count < 1024 * 128 { - text += text - } - - // warm up the encoder - self.scratchBuffer.setHuffmanEncoded(bytes: text.utf8) - - self.measureMetrics(HuffmanCodingTests.defaultPerformanceMetrics, automaticallyStartMeasuring: false) { - self.scratchBuffer.clear() - startMeasuring() - self.scratchBuffer.setHuffmanEncoded(bytes: text.utf8) - stopMeasuring() - } - } - - func testBasicDecodingPerformance() { - guard self.timeSensitiveTestEnabled else { return } - - let url = fixtureDirURL.appendingPathComponent("large_huffman_b64.txt") - guard let base64Data = try? Data(contentsOf: url) else { - XCTFail("Couldn't load fixture data") - return - } - guard let data = Data(base64Encoded: base64Data) else { - XCTFail("Couldn't decode base64 fixture data") - return - } - - var buffer = ByteBufferAllocator().buffer(capacity: data.count) - buffer.writeBytes(data) - - // warm up the decoder - XCTAssertNoThrow(try buffer.getHuffmanEncodedString(at: buffer.readerIndex, length: buffer.readableBytes)) - - self.measureMetrics(HuffmanCodingTests.defaultPerformanceMetrics, automaticallyStartMeasuring: false) { - startMeasuring() - _ = try! buffer.getHuffmanEncodedString(at: buffer.readerIndex, length: buffer.readableBytes) - } - } - - func testComplexEncodingPerformance() { - guard self.timeSensitiveTestEnabled else { return } - - var text = "午セイ谷高ぐふあト食71入ツエヘナ津県を類及オモ曜一購ごきわ致掲ぎぐず敗文輪へけり鯖審ヘ塊米卸呪おぴ。" - while text.utf8.count < 128 * 1024 { - text += text - } - - // warm up the encoder - self.scratchBuffer.setHuffmanEncoded(bytes: text.utf8) - - self.measureMetrics(HuffmanCodingTests.defaultPerformanceMetrics, automaticallyStartMeasuring: false) { - self.scratchBuffer.clear() - startMeasuring() - self.scratchBuffer.setHuffmanEncoded(bytes: text.utf8) - stopMeasuring() - } - } - - func testComplexDecodingPerformance() { - guard self.timeSensitiveTestEnabled else { return } - - let url = fixtureDirURL.appendingPathComponent("large_complex_huffman_b64.txt") - guard let base64Data = try? Data(contentsOf: url) else { - XCTFail("Couldn't load fixture data") - return - } - guard let data = Data(base64Encoded: base64Data) else { - XCTFail("Couldn't decode base64 fixture data") - return - } - - var buffer = ByteBufferAllocator().buffer(capacity: data.count) - buffer.writeBytes(data) - - // ensure the decoder table has been loaded - XCTAssertNoThrow(try buffer.getHuffmanEncodedString(at: buffer.readerIndex, length: buffer.readableBytes)) - - self.measureMetrics(HuffmanCodingTests.defaultPerformanceMetrics, automaticallyStartMeasuring: false) { - startMeasuring() - _ = try! buffer.getHuffmanEncodedString(at: buffer.readerIndex, length: buffer.readableBytes) - } - } - }