content stringlengths 1 103k ⌀ | path stringlengths 8 216 | filename stringlengths 2 179 | language stringclasses 15
values | size_bytes int64 2 189k | quality_score float64 0.5 0.95 | complexity float64 0 1 | documentation_ratio float64 0 1 | repository stringclasses 5
values | stars int64 0 1k | created_date stringdate 2023-07-10 19:21:08 2025-07-09 19:11:45 | license stringclasses 4
values | is_test bool 2
classes | file_hash stringlengths 32 32 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
//===--- Exclusivity.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// A set of tests for measuring the enforcement overhead of memory access\n// exclusivity rules.\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n // At -Onone\n // 25% swift_beginAccess\n // 15% tlv_get_addr\n // 15% swift_endAccess\n BenchmarkInfo(\n name: "ExclusivityGlobal",\n runFunction: run_accessGlobal,\n tags: [.runtime, .cpubench]\n ),\n // At -Onone\n // 23% swift_retain\n // 22% swift_release\n // 9% swift_beginAccess\n // 3% swift_endAccess\n BenchmarkInfo(\n name: "ExclusivityInMatSet",\n runFunction: run_accessInMatSet,\n tags: [.runtime, .cpubench, .unstable]\n ),\n // At -Onone\n // 25% swift_release\n // 23% swift_retain\n // 16% swift_beginAccess\n // 8% swift_endAccess\n BenchmarkInfo(\n name: "ExclusivityIndependent",\n runFunction: run_accessIndependent,\n tags: [.runtime, .cpubench]\n ),\n]\n\n// Initially these benchmarks only measure access checks at -Onone. In\n// the future, access checks will also be emitted at -O.\n\n// Measure memory access checks on a trivial global.\n// ---\n\npublic var globalCounter: Int = 0\n\n// TODO:\n// - Merge begin/endAccess when no calls intervene (~2x speedup).\n// - Move Swift runtime into the OS (~2x speedup).\n// - Whole module analysis can remove exclusivity checks (> 10x speedup now, 4x speedup with runtime in OS).\n// (The global's "public" qualifier should make the benchmark immune to this optimization.)\n@inline(never)\npublic func run_accessGlobal(_ n: Int) {\n globalCounter = 0\n for _ in 1...10000*n {\n globalCounter += 1\n }\n check(globalCounter == 10000*n)\n}\n\n// Measure memory access checks on a class property.\n//\n// Note: The end_unpaired_access forces a callback on the property's\n// materializeForSet!\n// ---\n\n// Hopefully the optimizer will not see this as "final" and optimize away the\n// materializeForSet.\npublic class C {\n public var counter = 0\n\n func inc() {\n counter += 1\n }\n}\n\n// Thunk \n@inline(never)\nfunc updateClass(_ c: C) {\n c.inc()\n}\n\n// TODO: Replacing materializeForSet accessors with yield-once\n// accessors should make the callback overhead go away.\n@inline(never)\npublic func run_accessInMatSet(_ n: Int) {\n let c = C()\n for _ in 1...10000*n {\n updateClass(c)\n }\n check(c.counter == 10000*n)\n}\n\n// Measure nested access to independent objects.\n//\n// A single access set is still faster than hashing for up to four accesses.\n// ---\n\nstruct Var {\n var val = 0\n}\n\n@inline(never)\nfunc update(a: inout Var, b: inout Var, c: inout Var, d: inout Var) {\n a.val += 1\n b.val += 1\n c.val += 1\n d.val += 1\n}\n\n@inline(never)\npublic func run_accessIndependent(_ n: Int) {\n var a = Var()\n var b = Var()\n var c = Var()\n var d = Var()\n let updateVars = {\n update(a: &a, b: &b, c: &c, d: &d)\n }\n for _ in 1...1000*n {\n updateVars()\n }\n check(a.val == 1000*n && b.val == 1000*n && c.val == 1000*n\n && d.val == 1000*n)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Exclusivity.swift | cpp_apple_swift_benchmark_single-source_Exclusivity.swift | Swift | 3,473 | 0.95 | 0.065217 | 0.430894 | python-kit | 608 | 2023-12-07T11:47:16.168932 | MIT | false | 6f3f505dbc85d80fe66562129a667706 |
//===--- ExistentialPerformance.swift -------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, change ExistentialPerformance.swift.gyb\n// and run scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\nimport TestsUtils\n\n// The purpose of these benchmarks is to evaluate different scenarios when\n// moving the implementation of existentials (protocol values) to heap based\n// copy-on-write buffers.\n//\n// The performance boost of `Ref4` vs `Ref3` is expected because copying the\n// existential only involves copying one reference of the heap based\n// copy-on-write buffer (outline case) that holds the struct vs copying the\n// individual fields of the struct in the inline case of `Ref3`.\n\nlet t: [BenchmarkCategory] = [.skip]\nlet ta: [BenchmarkCategory] = [.api, .Array, .skip]\n\npublic let benchmarks: [BenchmarkInfo] = [\n BenchmarkInfo(name: "Existential.method.1x.Ref1",\n runFunction: run_method1x, tags: t, setUpFunction: etRef1),\n BenchmarkInfo(name: "Existential.method.1x.Ref2",\n runFunction: run_method1x, tags: t, setUpFunction: etRef2),\n BenchmarkInfo(name: "Existential.method.1x.Ref3",\n runFunction: run_method1x, tags: t, setUpFunction: etRef3),\n BenchmarkInfo(name: "Existential.method.1x.Ref4",\n runFunction: run_method1x, tags: t, setUpFunction: etRef4),\n BenchmarkInfo(name: "Existential.method.1x.Val0",\n runFunction: run_method1x, tags: t, setUpFunction: etVal0),\n BenchmarkInfo(name: "Existential.method.1x.Val1",\n runFunction: run_method1x, tags: t, setUpFunction: etVal1),\n BenchmarkInfo(name: "Existential.method.1x.Val2",\n runFunction: run_method1x, tags: t, setUpFunction: etVal2),\n BenchmarkInfo(name: "Existential.method.1x.Val3",\n runFunction: run_method1x, tags: t, setUpFunction: etVal3),\n BenchmarkInfo(name: "Existential.method.1x.Val4",\n runFunction: run_method1x, tags: t, setUpFunction: etVal4),\n BenchmarkInfo(name: "Existential.method.2x.Ref1",\n runFunction: run_method2x, tags: t, setUpFunction: etRef1),\n BenchmarkInfo(name: "Existential.method.2x.Ref2",\n runFunction: run_method2x, tags: t, setUpFunction: etRef2),\n BenchmarkInfo(name: "Existential.method.2x.Ref3",\n runFunction: run_method2x, tags: t, setUpFunction: etRef3),\n BenchmarkInfo(name: "Existential.method.2x.Ref4",\n runFunction: run_method2x, tags: t, setUpFunction: etRef4),\n BenchmarkInfo(name: "Existential.method.2x.Val0",\n runFunction: run_method2x, tags: t, setUpFunction: etVal0),\n BenchmarkInfo(name: "Existential.method.2x.Val1",\n runFunction: run_method2x, tags: t, setUpFunction: etVal1),\n BenchmarkInfo(name: "Existential.method.2x.Val2",\n runFunction: run_method2x, tags: t, setUpFunction: etVal2),\n BenchmarkInfo(name: "Existential.method.2x.Val3",\n runFunction: run_method2x, tags: t, setUpFunction: etVal3),\n BenchmarkInfo(name: "Existential.method.2x.Val4",\n runFunction: run_method2x, tags: t, setUpFunction: etVal4),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Ref1",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etRef1),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Ref2",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etRef2),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Ref3",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etRef3),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Ref4",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etRef4),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Val0",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etVal0),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Val1",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etVal1),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Val2",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etVal2),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Val3",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etVal3),\n BenchmarkInfo(name: "Existential.Pass.method.1x.Val4",\n runFunction: run_Pass_method1x, tags: t, setUpFunction: etVal4),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Ref1",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etRef1),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Ref2",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etRef2),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Ref3",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etRef3),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Ref4",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etRef4),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Val0",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etVal0),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Val1",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etVal1),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Val2",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etVal2),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Val3",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etVal3),\n BenchmarkInfo(name: "Existential.Pass.method.2x.Val4",\n runFunction: run_Pass_method2x, tags: t, setUpFunction: etVal4),\n BenchmarkInfo(name: "Existential.Mutating.Ref1",\n runFunction: run_Mutating, tags: t, setUpFunction: etRef1),\n BenchmarkInfo(name: "Existential.Mutating.Ref2",\n runFunction: run_Mutating, tags: t, setUpFunction: etRef2),\n BenchmarkInfo(name: "Existential.Mutating.Ref3",\n runFunction: run_Mutating, tags: t, setUpFunction: etRef3),\n BenchmarkInfo(name: "Existential.Mutating.Ref4",\n runFunction: run_Mutating, tags: t, setUpFunction: etRef4),\n BenchmarkInfo(name: "Existential.Mutating.Val0",\n runFunction: run_Mutating, tags: t, setUpFunction: etVal0),\n BenchmarkInfo(name: "Existential.Mutating.Val1",\n runFunction: run_Mutating, tags: t, setUpFunction: etVal1),\n BenchmarkInfo(name: "Existential.Mutating.Val2",\n runFunction: run_Mutating, tags: t, setUpFunction: etVal2),\n BenchmarkInfo(name: "Existential.Mutating.Val3",\n runFunction: run_Mutating, tags: t, setUpFunction: etVal3),\n BenchmarkInfo(name: "Existential.Mutating.Val4",\n runFunction: run_Mutating, tags: t, setUpFunction: etVal4),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Ref1",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etRef1),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Ref2",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etRef2),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Ref3",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etRef3),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Ref4",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etRef4),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Val0",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etVal0),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Val1",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etVal1),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Val2",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etVal2),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Val3",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etVal3),\n BenchmarkInfo(name: "Existential.MutatingAndNonMutating.Val4",\n runFunction: run_MutatingAndNonMutating, tags: t, setUpFunction: etVal4),\n BenchmarkInfo(name: "Existential.Array.init.Ref1",\n runFunction: run_Array_init, tags: ta, setUpFunction: etRef1),\n BenchmarkInfo(name: "Existential.Array.init.Ref2",\n runFunction: run_Array_init, tags: ta, setUpFunction: etRef2),\n BenchmarkInfo(name: "Existential.Array.init.Ref3",\n runFunction: run_Array_init, tags: ta, setUpFunction: etRef3),\n BenchmarkInfo(name: "Existential.Array.init.Ref4",\n runFunction: run_Array_init, tags: ta, setUpFunction: etRef4),\n BenchmarkInfo(name: "Existential.Array.init.Val0",\n runFunction: run_Array_init, tags: ta, setUpFunction: etVal0),\n BenchmarkInfo(name: "Existential.Array.init.Val1",\n runFunction: run_Array_init, tags: ta, setUpFunction: etVal1),\n BenchmarkInfo(name: "Existential.Array.init.Val2",\n runFunction: run_Array_init, tags: ta, setUpFunction: etVal2),\n BenchmarkInfo(name: "Existential.Array.init.Val3",\n runFunction: run_Array_init, tags: ta, setUpFunction: etVal3),\n BenchmarkInfo(name: "Existential.Array.init.Val4",\n runFunction: run_Array_init, tags: ta, setUpFunction: etVal4),\n BenchmarkInfo(name: "Existential.Array.method.1x.Ref1",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caRef1),\n BenchmarkInfo(name: "Existential.Array.method.1x.Ref2",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caRef2),\n BenchmarkInfo(name: "Existential.Array.method.1x.Ref3",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caRef3),\n BenchmarkInfo(name: "Existential.Array.method.1x.Ref4",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caRef4),\n BenchmarkInfo(name: "Existential.Array.method.1x.Val0",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caVal0),\n BenchmarkInfo(name: "Existential.Array.method.1x.Val1",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caVal1),\n BenchmarkInfo(name: "Existential.Array.method.1x.Val2",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caVal2),\n BenchmarkInfo(name: "Existential.Array.method.1x.Val3",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caVal3),\n BenchmarkInfo(name: "Existential.Array.method.1x.Val4",\n runFunction: run_Array_method1x, tags: ta, setUpFunction: caVal4),\n BenchmarkInfo(name: "Existential.Array.method.2x.Ref1",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caRef1),\n BenchmarkInfo(name: "Existential.Array.method.2x.Ref2",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caRef2),\n BenchmarkInfo(name: "Existential.Array.method.2x.Ref3",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caRef3),\n BenchmarkInfo(name: "Existential.Array.method.2x.Ref4",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caRef4),\n BenchmarkInfo(name: "Existential.Array.method.2x.Val0",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caVal0),\n BenchmarkInfo(name: "Existential.Array.method.2x.Val1",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caVal1),\n BenchmarkInfo(name: "Existential.Array.method.2x.Val2",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caVal2),\n BenchmarkInfo(name: "Existential.Array.method.2x.Val3",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caVal3),\n BenchmarkInfo(name: "Existential.Array.method.2x.Val4",\n runFunction: run_Array_method2x, tags: ta, setUpFunction: caVal4),\n BenchmarkInfo(name: "Existential.Array.Mutating.Ref1",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caRef1),\n BenchmarkInfo(name: "Existential.Array.Mutating.Ref2",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caRef2),\n BenchmarkInfo(name: "Existential.Array.Mutating.Ref3",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caRef3),\n BenchmarkInfo(name: "Existential.Array.Mutating.Ref4",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caRef4),\n BenchmarkInfo(name: "Existential.Array.Mutating.Val0",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caVal0),\n BenchmarkInfo(name: "Existential.Array.Mutating.Val1",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caVal1),\n BenchmarkInfo(name: "Existential.Array.Mutating.Val2",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caVal2),\n BenchmarkInfo(name: "Existential.Array.Mutating.Val3",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caVal3),\n BenchmarkInfo(name: "Existential.Array.Mutating.Val4",\n runFunction: run_ArrayMutating, tags: ta, setUpFunction: caVal4),\n BenchmarkInfo(name: "Existential.Array.Shift.Ref1",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caRef1),\n BenchmarkInfo(name: "Existential.Array.Shift.Ref2",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caRef2),\n BenchmarkInfo(name: "Existential.Array.Shift.Ref3",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caRef3),\n BenchmarkInfo(name: "Existential.Array.Shift.Ref4",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caRef4),\n BenchmarkInfo(name: "Existential.Array.Shift.Val0",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caVal0),\n BenchmarkInfo(name: "Existential.Array.Shift.Val1",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caVal1),\n BenchmarkInfo(name: "Existential.Array.Shift.Val2",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caVal2),\n BenchmarkInfo(name: "Existential.Array.Shift.Val3",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caVal3),\n BenchmarkInfo(name: "Existential.Array.Shift.Val4",\n runFunction: run_ArrayShift, tags: ta, setUpFunction: caVal4),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Ref1",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caRef1),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Ref2",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caRef2),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Ref3",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caRef3),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Ref4",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caRef4),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Val0",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caVal0),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Val1",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caVal1),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Val2",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caVal2),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Val3",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caVal3),\n BenchmarkInfo(name: "Existential.Array.ConditionalShift.Val4",\n runFunction: run_ArrayConditionalShift, tags: ta, setUpFunction: caVal4),\n]\n\n// To exclude the setup overhead of existential array initialization,\n// these are setup functions that **create array** for each variant type.\nvar array: [Existential]!\nfunc ca<T: Existential>(_: T.Type) {\n array = Array(repeating: T(), count: 128)\n}\nfunc caVal0() { ca(Val0.self) }\nfunc caVal1() { ca(Val1.self) }\nfunc caVal2() { ca(Val2.self) }\nfunc caVal3() { ca(Val3.self) }\nfunc caVal4() { ca(Val4.self) }\nfunc caRef1() { ca(Ref1.self) }\nfunc caRef2() { ca(Ref2.self) }\nfunc caRef3() { ca(Ref3.self) }\nfunc caRef4() { ca(Ref4.self) }\n\n// `setUpFunctions` that determine which existential type will be tested\nvar existentialType: Existential.Type!\nfunc etVal0() { existentialType = Val0.self }\nfunc etVal1() { existentialType = Val1.self }\nfunc etVal2() { existentialType = Val2.self }\nfunc etVal3() { existentialType = Val3.self }\nfunc etVal4() { existentialType = Val4.self }\nfunc etRef1() { existentialType = Ref1.self }\nfunc etRef2() { existentialType = Ref2.self }\nfunc etRef3() { existentialType = Ref3.self }\nfunc etRef4() { existentialType = Ref4.self }\n\nprotocol Existential {\n init()\n func doIt() -> Bool\n func reallyDoIt() -> Bool\n mutating func mutateIt() -> Bool\n}\n\nfunc next(_ x: inout Int, upto mod: Int) {\n x = (x + 1) % (mod + 1)\n}\n\nstruct Val0 : Existential {\n func doIt() -> Bool {\n return true\n }\n func reallyDoIt() -> Bool {\n return true\n }\n mutating func mutateIt() -> Bool {\n return true\n }\n}\n\nstruct Val1 : Existential {\n var f0: Int = 0\n\n func doIt() -> Bool {\n return f0 == 0\n }\n func reallyDoIt() -> Bool {\n return true\n }\n mutating func mutateIt() -> Bool {\n next(&f0, upto: 1)\n return true\n }\n}\n\nstruct Val2 : Existential {\n var f0: Int = 0\n var f1: Int = 3\n\n func doIt() -> Bool {\n return f0 == 0\n }\n func reallyDoIt() -> Bool {\n return f0 == 0 && f1 == 3\n }\n mutating func mutateIt() -> Bool {\n next(&f0, upto: 1)\n next(&f1, upto: 3)\n return true\n }\n}\n\nstruct Val3 : Existential {\n var f0: Int = 0\n var f1: Int = 3\n var f2: Int = 7\n\n func doIt() -> Bool {\n return f0 == 0\n }\n func reallyDoIt() -> Bool {\n return f0 == 0 && f1 == 3 && f2 == 7\n }\n mutating func mutateIt() -> Bool {\n next(&f0, upto: 1)\n next(&f1, upto: 3)\n next(&f2, upto: 7)\n return true\n }\n}\n\nstruct Val4 : Existential {\n var f0: Int = 0\n var f1: Int = 3\n var f2: Int = 7\n var f3: Int = 13\n\n func doIt() -> Bool {\n return f0 == 0\n }\n func reallyDoIt() -> Bool {\n return f0 == 0 && f1 == 3 && f2 == 7 && f3 == 13\n }\n mutating func mutateIt() -> Bool {\n next(&f0, upto: 1)\n next(&f1, upto: 3)\n next(&f2, upto: 7)\n next(&f3, upto: 13)\n return true\n }\n}\n\nclass Klazz { // body same as Val2\n var f0: Int = 0\n var f1: Int = 3\n\n func doIt() -> Bool {\n return f0 == 0\n }\n func reallyDoIt() -> Bool {\n return f0 == 0 && f1 == 3\n }\n func mutateIt() -> Bool{\n next(&f0, upto: 1)\n next(&f1, upto: 3)\n return true\n }\n}\n\nstruct Ref1 : Existential {\n var f0: Klazz = Klazz()\n\n func doIt() -> Bool {\n return f0.doIt()\n }\n func reallyDoIt() -> Bool {\n return f0.reallyDoIt()\n }\n mutating func mutateIt() -> Bool{\n return f0.mutateIt()\n }\n}\n\nstruct Ref2 : Existential {\n var f0: Klazz = Klazz()\n var f1: Klazz = Klazz()\n\n func doIt() -> Bool {\n return f0.doIt()\n }\n func reallyDoIt() -> Bool {\n return f0.reallyDoIt()\n }\n mutating func mutateIt() -> Bool{\n return f0.mutateIt()\n }\n}\n\nstruct Ref3 : Existential {\n var f0: Klazz = Klazz()\n var f1: Klazz = Klazz()\n var f2: Klazz = Klazz()\n\n func doIt() -> Bool {\n return f0.doIt()\n }\n func reallyDoIt() -> Bool {\n return f0.reallyDoIt()\n }\n mutating func mutateIt() -> Bool{\n return f0.mutateIt()\n }\n}\n\nstruct Ref4 : Existential {\n var f0: Klazz = Klazz()\n var f1: Klazz = Klazz()\n var f2: Klazz = Klazz()\n var f3: Int = 0\n\n func doIt() -> Bool {\n return f0.doIt()\n }\n func reallyDoIt() -> Bool {\n return f0.reallyDoIt()\n }\n mutating func mutateIt() -> Bool{\n return f0.mutateIt()\n }\n}\n\n\n@inline(never)\nfunc passExistentialTwiceOneMethodCall(_ e0: Existential, _ e1: Existential)\n -> Bool {\n return e0.doIt() && e1.doIt()\n}\n\n@inline(never)\nfunc passExistentialTwiceTwoMethodCalls(_ e0: Existential, _ e1: Existential)\n -> Bool {\n return e0.doIt() && e1.doIt() && e0.reallyDoIt() && e1.reallyDoIt()\n}\n\nfunc run_method1x(_ n: Int) {\n let existential = existentialType.init()\n for _ in 0 ..< n * 20_000 {\n if !existential.doIt() {\n fatalError("expected true")\n }\n }\n}\n\nfunc run_method2x(_ n: Int) {\n let existential = existentialType.init()\n for _ in 0 ..< n * 20_000 {\n if !existential.doIt() || !existential.reallyDoIt() {\n fatalError("expected true")\n }\n }\n}\n\nfunc run_Pass_method1x(_ n: Int) {\n let existential = existentialType.init()\n let existential2 = existentialType.init()\n for _ in 0 ..< n * 20_000 {\n if !passExistentialTwiceOneMethodCall(existential, existential2) {\n fatalError("expected true")\n }\n }\n}\n\nfunc run_Pass_method2x(_ n: Int) {\n let existential = existentialType.init()\n let existential2 = existentialType.init()\n for _ in 0 ..< n * 20_000 {\n if !passExistentialTwiceTwoMethodCalls(existential, existential2) {\n fatalError("expected true")\n }\n }\n}\n\nfunc run_Mutating(_ n: Int) {\n var existential = existentialType.init()\n for _ in 0 ..< n * 10_000 {\n if !existential.mutateIt() {\n fatalError("expected true")\n }\n }\n}\n\nfunc run_MutatingAndNonMutating(_ n: Int) {\n var existential = existentialType.init()\n for _ in 0 ..< n * 10_000 {\n let _ = existential.doIt()\n if !existential.mutateIt() {\n fatalError("expected true")\n }\n }\n}\n\nfunc run_Array_init(_ n: Int) {\n\n for _ in 0 ..< n * 100 {\n blackHole(Array(repeating: existentialType.init(), count: 128))\n }\n}\n\nfunc run_Array_method1x(_ n: Int) {\n let existentialArray = array!\n for _ in 0 ..< n * 100 {\n for elt in existentialArray {\n if !elt.doIt() {\n fatalError("expected true")\n }\n }\n }\n}\n\nfunc run_Array_method2x(_ n: Int) {\n let existentialArray = array!\n for _ in 0 ..< n * 100 {\n for elt in existentialArray {\n if !elt.doIt() || !elt.reallyDoIt() {\n fatalError("expected true")\n }\n }\n }\n}\n\nfunc run_ArrayMutating(_ n: Int) {\n var existentialArray = array!\n for _ in 0 ..< n * 500 {\n for i in 0 ..< existentialArray.count {\n if !existentialArray[i].mutateIt() {\n fatalError("expected true")\n }\n }\n }\n}\n\nfunc run_ArrayShift(_ n: Int) {\n var existentialArray = array!\n for _ in 0 ..< n * 25 {\n for i in 0 ..< existentialArray.count-1 {\n existentialArray.swapAt(i, i+1)\n }\n }\n}\n\nfunc run_ArrayConditionalShift(_ n: Int) {\n var existentialArray = array!\n for _ in 0 ..< n * 25 {\n for i in 0 ..< existentialArray.count-1 {\n let curr = existentialArray[i]\n if curr.doIt() {\n existentialArray[i] = existentialArray[i+1]\n existentialArray[i+1] = curr\n }\n }\n }\n}\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ExistentialPerformance.swift | cpp_apple_swift_benchmark_single-source_ExistentialPerformance.swift | Swift | 22,166 | 0.95 | 0.052721 | 0.055249 | awesome-app | 641 | 2025-06-07T18:39:05.934661 | GPL-3.0 | false | 4cba352c10336dfc3232fcf4de6c0583 |
//===--- Fibonacci.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Fibonacci2",\n runFunction: run_Fibonacci,\n tags: [.algorithm])\n\nfunc _fibonacci(_ n: Int) -> Int {\n if (n <= 2) { return 1 }\n return _fibonacci(n - 2) + _fibonacci(n - 1)\n}\n\n@inline(never)\nfunc fibonacci(_ n: Int) -> Int {\n // This if prevents optimizer from computing return value of fibonacci(32)\n // at compile time.\n if getFalse() { return 0 }\n\n if (n <= 2) { return 1 }\n return _fibonacci(n - 2) + _fibonacci(n - 1)\n}\n\n@inline(never)\npublic func run_Fibonacci(_ N: Int) {\n let n = 24\n let ref_result = 46368\n var result = 0\n for _ in 1...N {\n result = fibonacci(n)\n if result != ref_result {\n break\n }\n }\n check(result == ref_result)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Fibonacci.swift | cpp_apple_swift_benchmark_single-source_Fibonacci.swift | Swift | 1,265 | 0.95 | 0.166667 | 0.309524 | python-kit | 861 | 2024-10-11T08:37:51.853022 | BSD-3-Clause | false | 910d658422f3f6298a7b111a9e2a33e3 |
//===--- FindStringNaive.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// Mini benchmark implementing a naive String search algorithm that\n// at the moment shows a lot of ARC traffic.\nlet t: [BenchmarkCategory] = [.String, .refcount]\n\nvar longStringFoFoFoFox: String?\nvar longArrayFoFoFoFox: [UInt8]?\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "FindString.Loop1.Substring",\n runFunction: runBenchLoop1Substring,\n tags: t,\n setUpFunction: {\n longStringFoFoFoFox = String(repeating: "fo", count: 5_000) + "fox <-- needle"\n }),\n BenchmarkInfo(\n name: "FindString.Rec3.String",\n runFunction: runBenchRecursive3String,\n tags: t,\n setUpFunction: {\n longStringFoFoFoFox = String(repeating: "fo", count: 500) + "fox <-- needle"\n }),\n BenchmarkInfo(\n name: "FindString.Rec3.Substring",\n runFunction: runBenchRecursive3Substring,\n tags: t,\n setUpFunction: {\n longStringFoFoFoFox = String(repeating: "fo", count: 500) + "fox <-- needle"\n }),\n BenchmarkInfo(\n name: "FindString.Loop1.Array",\n runFunction: runBenchLoop1Array,\n tags: t,\n setUpFunction: {\n longArrayFoFoFoFox = []\n longArrayFoFoFoFox!.reserveCapacity(1_100_000)\n for _ in 0 ..< 500_000 {\n longArrayFoFoFoFox!.append(contentsOf: "fo".utf8)\n }\n longArrayFoFoFoFox!.append(contentsOf: "fox <-- needle".utf8)\n }),\n BenchmarkInfo(\n name: "FindString.Rec3.Array",\n runFunction: runBenchRecursive3ArrayOfUTF8,\n tags: t,\n setUpFunction: {\n longArrayFoFoFoFox = []\n longArrayFoFoFoFox!.reserveCapacity(11_000)\n for _ in 0 ..< 5_000 {\n longArrayFoFoFoFox!.append(contentsOf: "fo".utf8)\n }\n longArrayFoFoFoFox!.append(contentsOf: "fox <-- needle".utf8)\n }),\n]\n\nfunc findOne<S: StringProtocol>(\n _ string: S,\n needle: Character\n) -> String.Index? {\n var index = string.startIndex\n while index < string.endIndex {\n let nextIndex = string.index(after: index)\n if string[index] == needle {\n return index\n }\n index = nextIndex\n }\n return nil\n}\n\nfunc findThreeRecursive<S: StringProtocol>(\n _ string: S,\n needle1: Character,\n needle2: Character?,\n needle3: Character?\n) -> String.Index? {\n var index = string.startIndex\n while index < string.endIndex {\n let nextIndex = string.index(after: index)\n if string[index] == needle1 {\n // Check subsequent needles recursively (if applicable)\n guard let needle2 = needle2 else { return index }\n\n if findThreeRecursive(\n string[nextIndex...].prefix(2), needle1: needle2, needle2: needle3, needle3: nil\n ) == nextIndex {\n return index\n }\n }\n index = nextIndex\n }\n return nil\n}\n\nfunc findOneOnUTF8Collection<Bytes: Collection>(\n _ string: Bytes,\n needle: UInt8\n) -> Bytes.Index? where Bytes.Element == UInt8 {\n var index = string.startIndex\n while index < string.endIndex {\n let nextIndex = string.index(after: index)\n if string[index] == needle {\n return index\n }\n index = nextIndex\n }\n return nil\n}\n\nfunc findThreeOnUTF8Collection<Bytes: Collection>(\n _ string: Bytes,\n needle1: UInt8,\n needle2: UInt8?,\n needle3: UInt8?\n) -> Bytes.Index? where Bytes.Element == UInt8 {\n var index = string.startIndex\n while index < string.endIndex {\n let nextIndex = string.index(after: index)\n if string[index] == needle1 {\n // Check subsequent needles recursively (if applicable)\n guard let needle2 = needle2 else { return index }\n\n if findThreeOnUTF8Collection(\n string[nextIndex...].prefix(2), needle1: needle2, needle2: needle3, needle3: nil\n ) == nextIndex {\n return index\n }\n }\n index = nextIndex\n }\n return nil\n}\n\n@inline(never)\nfunc runBenchLoop1Substring(iterations: Int) {\n for _ in 0 ..< iterations {\n precondition(findOne(longStringFoFoFoFox![...], needle: "x") != nil)\n }\n}\n\n@inline(never)\nfunc runBenchLoop1Array(iterations: Int) {\n for _ in 0 ..< iterations {\n precondition(findOneOnUTF8Collection(longArrayFoFoFoFox!, needle: UInt8(ascii: "x")) != nil)\n }\n}\n\n@inline(never)\nfunc runBenchRecursive3Substring(iterations: Int) {\n for _ in 0 ..< iterations {\n precondition(findThreeRecursive(longStringFoFoFoFox![...], needle1: "f", needle2: "o", needle3: "x") != nil)\n }\n}\n\n@inline(never)\nfunc runBenchRecursive3String(iterations: Int) {\n for _ in 0 ..< iterations {\n precondition(findThreeRecursive(longStringFoFoFoFox!, needle1: "f", needle2: "o", needle3: "x") != nil)\n }\n}\n\n@inline(never)\nfunc runBenchRecursive3ArrayOfUTF8(iterations: Int) {\n for _ in 0 ..< iterations {\n precondition(findThreeOnUTF8Collection(longArrayFoFoFoFox!,\n needle1: UInt8(ascii: "f"),\n needle2: UInt8(ascii: "o"),\n needle3: UInt8(ascii: "x")) != nil)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_FindStringNaive.swift | cpp_apple_swift_benchmark_single-source_FindStringNaive.swift | Swift | 5,339 | 0.95 | 0.11413 | 0.088757 | react-lib | 475 | 2023-11-29T16:51:34.765597 | MIT | false | 4c7f3c976c4087fbf1b727e9ab9536ca |
//===--- FlattenDistanceFromTo.swift --------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "FlattenDistanceFromTo.Array.Array.04.04",\n runFunction: { with(arrayArray04x04, $0) },\n tags: [.validation, .api],\n setUpFunction: { blackHole(arrayArray04x04) }),\n\n BenchmarkInfo(\n name: "FlattenDistanceFromTo.Array.Array.04x08",\n runFunction: { with(arrayArray04x08, $0) },\n tags: [.validation, .api],\n setUpFunction: { blackHole(arrayArray04x08) }),\n\n BenchmarkInfo(\n name: "FlattenDistanceFromTo.Array.Array.08.04",\n runFunction: { with(arrayArray08x04, $0) },\n tags: [.validation, .api],\n setUpFunction: { blackHole(arrayArray08x04) }),\n\n BenchmarkInfo(\n name: "FlattenDistanceFromTo.Array.Array.08.08",\n runFunction: { with(arrayArray08x08, $0) },\n tags: [.validation, .api],\n setUpFunction: { blackHole(arrayArray08x08) }),\n \n BenchmarkInfo(\n name: "FlattenDistanceFromTo.Array.String.04.04",\n runFunction: { with(arrayString04x04, $0) },\n tags: [.validation, .api],\n setUpFunction: { blackHole(arrayString04x04) }),\n\n BenchmarkInfo(\n name: "FlattenDistanceFromTo.Array.String.04.08",\n runFunction: { with(arrayString04x08, $0) },\n tags: [.validation, .api],\n setUpFunction: { blackHole(arrayString04x08) }),\n\n BenchmarkInfo(\n name: "FlattenDistanceFromTo.Array.String.08.04",\n runFunction: { with(arrayString08x04, $0) },\n tags: [.validation, .api],\n setUpFunction: { blackHole(arrayString08x04) }),\n\n BenchmarkInfo(\n name: "FlattenDistanceFromTo.Array.String.08.08",\n runFunction: { with(arrayString08x08, $0) },\n tags: [.validation, .api],\n setUpFunction: { blackHole(arrayString08x08) }),\n]\n\n// MARK: - Array Array\n\nfunc makeArrayArray(_ outer: Int, _ inner: Int) -> FlattenSequence<[[UInt8]]> {\n Array(repeating: Array(repeating: 123, count: inner), count: outer).joined()\n}\n\nlet arrayArray04x04 = makeArrayArray(04, 04)\nlet arrayArray04x08 = makeArrayArray(04, 08)\nlet arrayArray08x04 = makeArrayArray(08, 04)\nlet arrayArray08x08 = makeArrayArray(08, 08)\n\n@inline(never)\npublic func with(_ collection: FlattenSequence<[[UInt8]]>, _ iterations: Int) {\n var value = 0 as Int\n \n for _ in 0 ..< iterations {\n for a in collection.indices {\n for b in collection.indices {\n value &+= collection.distance(from: a, to: b)\n value &+= collection.distance(from: b, to: a)\n }\n }\n }\n\n blackHole(value == 0)\n}\n\n// MARK: - Array String\n\nfunc makeArrayString(_ outer: Int, _ inner: Int) -> FlattenSequence<[String]> {\n Array(repeating: String(repeating: "0", count: inner), count: outer).joined()\n}\n\nlet arrayString04x04 = makeArrayString(04, 04)\nlet arrayString04x08 = makeArrayString(04, 08)\nlet arrayString08x04 = makeArrayString(08, 04)\nlet arrayString08x08 = makeArrayString(08, 08)\n\n@inline(never)\npublic func with(_ collection: FlattenSequence<[String]>, _ iterations: Int) {\n var value = 0 as Int\n \n for _ in 0 ..< iterations {\n for a in collection.indices {\n for b in collection.indices {\n value &+= collection.distance(from: a, to: b)\n value &+= collection.distance(from: b, to: a)\n }\n }\n }\n\n blackHole(value == 0)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_FlattenDistanceFromTo.swift | cpp_apple_swift_benchmark_single-source_FlattenDistanceFromTo.swift | Swift | 3,682 | 0.95 | 0.068376 | 0.135417 | node-utils | 369 | 2025-06-29T02:13:55.250154 | GPL-3.0 | false | 4fa022848ffed9c2c00ec78fc6c63df2 |
//===--- FlattenList.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "FlattenListLoop",\n runFunction: run_FlattenListLoop,\n tags: [.api, .validation],\n setUpFunction: { blackHole(inputArray) }),\n\n BenchmarkInfo(\n name: "FlattenListFlatMap",\n runFunction: run_FlattenListFlatMap,\n tags: [.api, .validation],\n setUpFunction: { blackHole(inputArray) }),\n]\n\nlet inputArray: [(Int, Int, Int, Int)] = (0..<(1<<16)).map { _ in\n (5, 6, 7, 8)\n}\n\nfunc flattenFlatMap(_ input: [(Int, Int, Int, Int)]) -> [Int] {\n return input.flatMap { [$0.0, $0.1, $0.2, $0.3] }\n}\n\nfunc flattenLoop(_ input: [(Int, Int, Int, Int)]) -> [Int] {\n var flattened: [Int] = []\n flattened.reserveCapacity(input.count * 4)\n\n for (x, y, z, w) in input {\n flattened.append(x)\n flattened.append(y)\n flattened.append(z)\n flattened.append(w)\n }\n\n return flattened\n}\n\n@inline(never)\npublic func run_FlattenListLoop(_ n: Int) {\n for _ in 0..<5*n {\n blackHole(flattenLoop(inputArray))\n }\n}\n\n@inline(never)\npublic func run_FlattenListFlatMap(_ n: Int) {\n for _ in 1...5*n {\n blackHole(flattenFlatMap(inputArray))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_FlattenList.swift | cpp_apple_swift_benchmark_single-source_FlattenList.swift | Swift | 1,647 | 0.95 | 0.079365 | 0.207547 | react-lib | 71 | 2024-10-21T19:43:18.086550 | Apache-2.0 | false | 0d9ef22af77d3c86a588050bd2b14a0a |
//===--- FloatingPointConversion.swift ------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "ConvertFloatingPoint.MockFloat64ToDouble",\n runFunction: run_ConvertFloatingPoint_MockFloat64ToDouble,\n tags: [.validation, .api],\n setUpFunction: { blackHole(mockFloat64s) }),\n BenchmarkInfo(\n name: "ConvertFloatingPoint.MockFloat64Exactly",\n runFunction: run_ConvertFloatingPoint_MockFloat64Exactly,\n tags: [.validation, .api],\n setUpFunction: { blackHole(mockFloat64s) }),\n BenchmarkInfo(\n name: "ConvertFloatingPoint.MockFloat64Exactly2",\n runFunction: run_ConvertFloatingPoint_MockFloat64Exactly2,\n tags: [.validation, .api],\n setUpFunction: { blackHole(mockFloat64s) }),\n BenchmarkInfo(\n name: "ConvertFloatingPoint.MockFloat64ToInt64",\n runFunction: run_ConvertFloatingPoint_MockFloat64ToInt64,\n tags: [.validation, .api],\n setUpFunction: { blackHole(mockFloat64s) }),\n]\n\nprotocol MockBinaryFloatingPoint: BinaryFloatingPoint {\n associatedtype _Value: BinaryFloatingPoint\n var _value: _Value { get set }\n init(_ _value: _Value)\n}\n\nextension MockBinaryFloatingPoint {\n static var exponentBitCount: Int { _Value.exponentBitCount }\n static var greatestFiniteMagnitude: Self {\n Self(_Value.greatestFiniteMagnitude)\n }\n static var infinity: Self { Self(_Value.infinity) }\n static var leastNonzeroMagnitude: Self { Self(_Value.leastNonzeroMagnitude) }\n static var leastNormalMagnitude: Self { Self(_Value.leastNormalMagnitude) }\n static var nan: Self { Self(_Value.nan) }\n static var pi: Self { Self(_Value.pi) }\n static var signalingNaN: Self { Self(_Value.signalingNaN) }\n static var significandBitCount: Int { _Value.significandBitCount }\n \n static func + (lhs: Self, rhs: Self) -> Self { Self(lhs._value + rhs._value) }\n static func += (lhs: inout Self, rhs: Self) { lhs._value += rhs._value }\n static func - (lhs: Self, rhs: Self) -> Self { Self(lhs._value - rhs._value) }\n static func -= (lhs: inout Self, rhs: Self) { lhs._value -= rhs._value }\n static func * (lhs: Self, rhs: Self) -> Self { Self(lhs._value * rhs._value) }\n static func *= (lhs: inout Self, rhs: Self) { lhs._value *= rhs._value }\n static func / (lhs: Self, rhs: Self) -> Self { Self(lhs._value / rhs._value) }\n static func /= (lhs: inout Self, rhs: Self) { lhs._value /= rhs._value }\n \n init(_ value: Int) { self.init(_Value(value)) }\n init(_ value: Float) { self.init(_Value(value)) }\n init(_ value: Double) { self.init(_Value(value)) }\n#if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64))\n init(_ value: Float80) { self.init(_Value(value)) }\n#endif\n init(integerLiteral value: _Value.IntegerLiteralType) {\n self.init(_Value(integerLiteral: value))\n }\n init(floatLiteral value: _Value.FloatLiteralType) {\n self.init(_Value(floatLiteral: value))\n }\n init(sign: FloatingPointSign, exponent: _Value.Exponent, significand: Self) {\n self.init(\n _Value(sign: sign, exponent: exponent, significand: significand._value))\n }\n init(\n sign: FloatingPointSign,\n exponentBitPattern: _Value.RawExponent,\n significandBitPattern: _Value.RawSignificand\n ) {\n self.init(\n _Value(\n sign: sign,\n exponentBitPattern: exponentBitPattern,\n significandBitPattern: significandBitPattern))\n }\n \n var binade: Self { Self(_value.binade) }\n var exponent: _Value.Exponent { _value.exponent }\n var exponentBitPattern: _Value.RawExponent { _value.exponentBitPattern }\n var isCanonical: Bool { _value.isCanonical }\n var isFinite: Bool { _value.isFinite }\n var isInfinite: Bool { _value.isInfinite }\n var isNaN: Bool { _value.isNaN }\n var isNormal: Bool { _value.isNormal }\n var isSignalingNaN: Bool { _value.isSignalingNaN }\n var isSubnormal: Bool { _value.isSubnormal }\n var isZero: Bool { _value.isZero }\n var magnitude: Self { Self(_value.magnitude) }\n var nextDown: Self { Self(_value.nextDown) }\n var nextUp: Self { Self(_value.nextUp) }\n var sign: FloatingPointSign { _value.sign }\n var significand: Self { Self(_value.significand) }\n var significandBitPattern: _Value.RawSignificand {\n _value.significandBitPattern\n }\n var significandWidth: Int { _value.significandWidth }\n var ulp: Self { Self(_value.ulp) }\n \n mutating func addProduct(_ lhs: Self, _ rhs: Self) {\n _value.addProduct(lhs._value, rhs._value)\n }\n func advanced(by n: _Value.Stride) -> Self { Self(_value.advanced(by: n)) }\n func distance(to other: Self) -> _Value.Stride {\n _value.distance(to: other._value)\n }\n mutating func formRemainder(dividingBy other: Self) {\n _value.formRemainder(dividingBy: other._value)\n }\n mutating func formSquareRoot() { _value.formSquareRoot() }\n mutating func formTruncatingRemainder(dividingBy other: Self) {\n _value.formTruncatingRemainder(dividingBy: other._value)\n }\n func isEqual(to other: Self) -> Bool { _value.isEqual(to: other._value) }\n func isLess(than other: Self) -> Bool { _value.isLess(than: other._value) }\n func isLessThanOrEqualTo(_ other: Self) -> Bool {\n _value.isLessThanOrEqualTo(other._value)\n }\n mutating func round(_ rule: FloatingPointRoundingRule) { _value.round(rule) }\n}\n\nstruct MockFloat64: MockBinaryFloatingPoint {\n var _value: Double\n init(_ _value: Double) { self._value = _value }\n}\n\nstruct MockFloat32: MockBinaryFloatingPoint {\n var _value: Float\n init(_ _value: Float) { self._value = _value }\n}\n\nlet doubles = [\n 1.8547832857295, 26.321549267719135, 98.9544480962058, 73.70286973782363,\n 82.04918555938816, 76.38902969312758, 46.35647857011161, 64.0821426030317,\n 97.82373347320156, 55.742361037720634, 23.677941665488856, 93.7347588108058,\n 80.72657040828412, 32.137580733275826, 64.78192587530002, 21.459686568896863,\n 24.88407660280718, 85.25905561999171, 12.858847331083556, 29.418845887252864,\n 67.64627066438761, 68.09883494078815, 57.781587230862094, 63.38335631088038,\n 83.31376661495327, 87.45936846358906, 0.6757674136841918, 86.45465036820696,\n 84.72715137492781, 82.67894289189142, 26.1667640621554, 21.24895661442493,\n 65.06399183516027, 90.06549073883058, 59.2736650501005, 94.5800380563246,\n 84.22617424003917, 26.93158630395639, 9.069952095976841, 96.10067836567679,\n 62.60505762081415, 29.57878462599286, 66.06040114311294, 51.709999429326636,\n 64.79777579583545, 45.25948795832151, 94.31492354198335, 52.31096166433902,\n]\n\nlet mockFloat64s = doubles.map { MockFloat64($0) }\n\n// See also: test/SILOptimizer/floating_point_conversion.swift\n\n@inline(never)\npublic func run_ConvertFloatingPoint_MockFloat64ToDouble(_ n: Int) {\n for _ in 0..<(n * 100) {\n for element in mockFloat64s {\n let f = Double(identity(element))\n blackHole(f)\n }\n }\n}\n\n@inline(__always)\nfunc convert<\n T: BinaryFloatingPoint, U: BinaryFloatingPoint\n>(exactly value: T, to: U.Type) -> U? {\n U(exactly: value)\n}\n\n@inline(never)\npublic func run_ConvertFloatingPoint_MockFloat64Exactly(_ n: Int) {\n for _ in 0..<(n * 25) {\n for element in mockFloat64s {\n let f = convert(exactly: identity(element), to: Double.self)\n blackHole(f)\n }\n }\n}\n\n@inline(never)\npublic func run_ConvertFloatingPoint_MockFloat64Exactly2(_ n: Int) {\n for _ in 0..<(n * 25) {\n for element in mockFloat64s {\n let f = convert(exactly: identity(element), to: MockFloat32.self)\n blackHole(f)\n }\n }\n}\n\n@inline(never)\npublic func run_ConvertFloatingPoint_MockFloat64ToInt64(_ n: Int) {\n for _ in 0..<(n * 1000) {\n for element in mockFloat64s {\n let i = Int64(identity(element))\n blackHole(i)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_FloatingPointConversion.swift | cpp_apple_swift_benchmark_single-source_FloatingPointConversion.swift | Swift | 8,061 | 0.95 | 0.051887 | 0.072165 | react-lib | 786 | 2024-01-17T05:58:35.370782 | MIT | false | 205a804b9c45c91c30db12ac70c93a71 |
//===--- FloatingPointParsing.swift -----------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test verifies the performance of parsing a floating point value\n// from a String.\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "ParseFloat.Float.Exp",\n runFunction: run_ParseFloatExp,\n tags: [.validation, .api, .runtime, .String]),\n\n BenchmarkInfo(\n name: "ParseFloat.Double.Exp",\n runFunction: run_ParseDoubleExp,\n tags: [.validation, .api, .runtime, .String]),\n\n BenchmarkInfo(\n name: "ParseFloat.Float80.Exp",\n runFunction: run_ParseFloat80Exp,\n tags: [.validation, .api, .runtime, .String]),\n\n BenchmarkInfo(\n name: "ParseFloat.Float.Uniform",\n runFunction: run_ParseFloatUniform,\n tags: [.validation, .api, .runtime, .String]),\n\n BenchmarkInfo(\n name: "ParseFloat.Double.Uniform",\n runFunction: run_ParseDoubleUniform,\n tags: [.validation, .api, .runtime, .String]),\n\n BenchmarkInfo(\n name: "ParseFloat.Float80.Uniform",\n runFunction: run_ParseFloat80Uniform,\n tags: [.validation, .api, .runtime, .String]),\n]\n\n/// The 'Exp' test:\n\n/// Generates values following a truncated exponential distribution on 0...1000, \n/// each rounded to a number of significant digits uniformly selected from \n/// 1...6 (Float), 1...15 (Double) and 1...18 (Float80). \n/// This is a good representative sample of "well-scaled" values humans actually\n/// write in programs; in particular, it includes good coverage for integer values\n/// and values with short decimal parts.\n\n// func genExpDistributedFloat(significantDigits: Int) -> String {\n// let value = exp(Float80.random(in: 0...log(1000.0)))\n// return String(format: "%.\(significantDigits)f", Double(value))\n// }\n\n/// Each workload contains 100 elements generated from the above function.\n\nlet floatExpWorkload = [\n "840.23812", "15.9082", "319.784", "13.14857", "5.42759",\n "901.771", "339.6", "7.27", "126.88", "326.08923", "18.2804",\n "189.8467", "330.628", "8.272461", "19.337", "12.0082",\n "29.6085", "27.4508", "5.14013", "725.388972", "124.102",\n "13.315556", "21.288", "45.4670", "88.7246", "6.16",\n "1.506155", "2.16918", "779.120", "22.89751", "15.33395",\n "59.575817", "2.73305", "203.04", "321.08", "148.419",\n "249.675", "579.453", "222.2", "153.62548", "305.501",\n "96.3", "28.55095", "145.377249", "2.53048", "1.0",\n "293.2052", "2.1", "814.091552", "157.45375", "15.0",\n "1.304", "8.88", "799.458180", "11.3", "1.5645",\n "25.69062", "569.28", "2.6464", "173.792970", "6.25",\n "344.54", "2.09610", "3.547", "409.860",\n "65.866038", "3.64", "2.7", "62.304", "67.7729",\n "19.0638", "2.8", "8.89508", "20.04", "1.054648",\n "3.5479", "5.203191", "52.11968", "326.39", "43.027",\n "82.15620", "178.519010", "1.3", "5.40", "387.41",\n "500.5", "5.96", "1.7740", "96.48818", "889.583",\n "96.92098", "6.760", "199.441", "510.905", "307.726",\n "87.9055", "11.7", "6.487537", "119.1", "5.8"\n]\n\nlet doubleExpWorkload = [\n "339.91", "662.95264138", "590.3312546", "44.58449489426322", "1.61025794592574",\n "266.29744353690", "34.14542", "144.968532801343116", "1.790721486700", "609.0086620368", \n "1.79655054299720", "138.906589772754131", "1.3663343399933", "3.018134440821", "14.7117491216652", \n "97.0", "28.630149748915", "5.4", "29.7639", "4.520193", \n "43.574150740143", "21.26131766279", "8.332799002305356", "70.267", "792.71364", \n "987.54396679201125", "301.4300850", "707.7375522552", "3.350899864", "41.99", \n "78.051", "2.5251720", "28.171984464058", "6.115905648", "31.7", \n "2.90316715974825", "3.49235954808", "13.76", "3.2", "32.465845", \n "460.84828154", "1.0268532933", "79.607954332859777", "173.25041830", "49.0888", \n "23.2264", "130.018100263319411", "301.8", "1.707", "2.220651", \n "11.9744168", "13.50610", "83.276270711070708", "1.207", "11.507359", \n "887.81742700364475", "46.8051834077896", "174.367548608815781", "19.8671230", "5.0432", \n "3.927758869", "1.6393532610", "232.5", "17.77417107", "94.1453702714822", \n "746.2908548477199", "28.9832376533851", "1.7432454399", "96.15", "484.00318952955", \n "14.90238658606421", "243.704906310113", "29.5307828313724", "19.200405681021813", "24.1717308", \n "2.7453085963749", "2.856", "677.940804020", "221.57146165", "31.5891",\n "350.74206", "3.06588790579", "171.404", "46.106851", "590.3917781324", \n "829.052362588", "2.32566173", "7.0098461186", "306.11702882946065", "17.4345632593715", \n "899.3720935006996", "108.31212", "3.703786329", "48.81100281168", "27.41503", \n "169.15383", "1.978568", "3.68994208914", "29.4322212731893", "4.8719352"\n]\n\nlet float80ExpWorkload = [\n "6.77555058241", "147.74", "6.03", "507.6033533228630859", "100.7", \n "11.46", "3.264282911002", "85.7858847516568", "34.4300032", "4.9957", \n "198.3958760", "87.67549428326", "205.373035358974988", "27.93", "831.999235134615", \n "46.886425395152", "5.77789", "89.564807063568139256", "3.85398054", "1.021", \n "592.504", "1.802084399", "486.4972328197284", "5.22490700277", "29.917340694598", \n "181.48302719", "75.74373681671689", "30.48161373580532", "1.24544077730", "1.2", \n "10.426", "55.37308819", "1.87502584", "3.1486", "9.2794677633", \n "24.59858334079387632", "20.2896643", "4.6", "9.017375215972097", "163.1", \n "5.50921892286", "9.93079", "13.320762298", "3.194056167117689693", "211.6671712762052380", \n "347.0356", "209.66", "13.170751077618", "34.568", "330.5",\n "41.388619513", "625.5176", "7.3199072376", "2.40", "334.210711370", \n "10.790469414612726240", "2.051865559526", "374.34104357856199", "1.444672057", "182.15138835680261", \n "1.549898719", "2.2", "3.5960392119", "220.3919", "128.45273", \n "955.052925", "441.738166", "21.365", "28.5534801613", "124.1", \n "449.252220495138", "608.587461250119532", "107.88473705800", "2.085422", "2.5", \n "121.0005042322", "5.4402224803576962", "90.46", "40.646406742621564945", "70.79133", \n "4.59801271236", "1.893481804014", "17.52333", "1.3195086968", "46.70781", \n "14.59891931096853", "402.75", "158.0343", "7.152603207", "7.3637945245", \n "15.6", "545.740720800777012", "242.172569", "1.73940415531105", "151.14631658", \n "26.5256384449273490", "135.236", "12.886101", "47.596174", "1.831407510"\n]\n\n/// The 'Uniform' test:\n\n/// Generates values made up of uniform decimal significands with 9, 17 and 21 \n/// digits and exponents uniform on the valid range. This is a stress test \n/// for rounding, and covers all the worst cases for tables generated by programs.\n/// The exponent range is -45...38 for Floats, -324...308 for Doubles, and \n/// -4951...4932 for Float80.\n// func genUniformFloat(significandDigits: Int, exponentRange: ClosedRange<Int>) -> String {\n// let afterDecimalPoint = (0..<significandDigits).map { _ in String(Int.random(in: 0...9)) }.joined()\n// let sign = ["", "-", "+"].randomElement()!\n// return "\(sign)\(Int.random(in: 1...9)).\(afterDecimalPoint)e\(exponentRange.randomElement()!)"\n// }\n\n/// Each workload contains 100 elements generated from the above function,\n/// along with five inf/nan/invalid tests.\n\nlet floatUniformWorkload = [\n "+1.253892113e-32", "+5.834995733e-41", "5.262096122e-17", "+4.917053817e-37", "8.535406338e-34", \n "2.152837278e10", "-5.212739043e-16", "+9.799669278e-27", "+8.678995824e-6", "-5.965172043e26", \n "-8.420371743e-10", "1.968856825e-8", "1.521071839e-19", "+1.048728457e-15", "-5.657219736e10", \n "-7.664702071e-34", "+3.282753652e15", "-5.032906928e26", "-3.024685077e29", "+7.972511327e-22",\n "-3.941547478e-19", "-2.424139629e4", "+1.222228289e2", "+9.872675983e4", "+8.505353502e-43", \n "7.315998745e12", "-2.879924852e-38", "5.567658036e21", "5.751274848e-39", "-2.098314138e8", \n "-2.295512125e-13", "-9.261977483e3", "-7.717209557e26", "+6.563403126e38", "-6.988491389e-45", \n "3.318738022e21", "5.534799334e16", "7.236228752e0", "+6.134225015e-26", "-1.801539431e-3", \n "-8.763001980e37", "-4.810306387e-30", "-8.902359860e5", "-4.654434339e17", "4.103749478e11", \n "+1.624005001e0", "+6.810516979e-8", "+4.509584369e0", "7.115062319e15", "-3.275835669e24", \n "-2.225975117e17", "+9.765601399e-27", "9.271660327e13", "-7.957489335e4", "+1.279815043e-30", \n "-6.140235958e-3", "+2.925804509e-11", "-2.902478935e-36", "+2.870673595e-37", "+8.788759496e-20", \n "+7.279719040e13", "-9.516217056e20", "2.306171183e21", "-2.655002939e22", "-8.678845371e32", \n "6.086700440e20", "+6.768130785e12", "1.675300343e11", "+8.156722194e-16", "-6.040145895e35", \n "-6.928961416e-26", "-5.119323586e27", "-4.566748978e-5", "-3.394147506e-7", "6.171944831e-19", \n "+8.883811091e-11", "-3.390953266e-44", "-1.912771939e-7", "+8.506344503e-23", "-3.437927939e21", \n "-3.515331652e1", "8.610555796e9", "2.340195107e-20", "+9.018470750e-42", "+8.321248518e27", \n "-6.959418594e32", "-5.342372027e21", "+2.744186726e-24", "9.948785682e-37", "+6.310898794e-6", \n "-2.477472268e16", "8.590689853e1", "+7.811554461e-24", "+1.508151084e17", "3.071428780e-7",\n "4.545415458e-9", "7.075010280e11", "+8.616159616e-29", "4.613265893e-10", "7.770003218e-33",\n "+inf", "Invalid", "nan", "NAN", "snan"\n]\n\nlet doubleUniformWorkload = [\n "-5.099347166e-78", "3.584151187e-255", "-7.555973282e17", "+6.217083912e-164", "-6.063585254e8", \n "-5.374097872e-252", "2.688487062e208", "+1.030241589e-272", "2.120162986e-50", "-2.617585299e-69",\n "8.560348373e282", "4.323584117e-168", "5.899559411e215", "+3.630548207e220", "-8.420738030e-73", \n "-6.832994185e-129", "-9.751163985e90", "-3.923652856e222", "-5.337925604e-12", "+4.360166940e-75", \n "+6.207675792e-164", "-8.275068142e-195", "+3.318047866e-71", "-9.162983038e197", "+9.330784575e-147", \n "9.208831616e-322", "-5.688921689e270", "+2.871328480e-258", "-8.071161900e261", "-4.191368176e222", \n "+5.792498976e-167", "5.835667380e235", "+9.402094050e6", "2.079961640e180", "+4.037655106e86", \n "-1.267141442e106", "+2.361395667e138", "+2.101128051e142", "5.301258292e42", "-8.822348131e-280", \n "-3.775817054e208", "-5.080405399e93", "+9.686534601e-77", "4.586641905e-175", "3.135576124e77", \n "4.688137331e138", "+6.893752397e-189", "6.812711913e278", "3.812796443e115", "+3.744289703e7", \n "+5.932500106e157", "+4.846313692e16", "-8.881077959e-290", "+1.535288334e-275", "7.250519901e-75",\n "2.787321374e41", "+3.519991812e-183", "+7.589975072e79", "5.848655303e122", "-3.328972789e161", \n "-2.190752323e104", "8.864042297e147", "+8.584292050e-239", "-7.972816817e219", "9.352363266e-99", \n "+9.435082870e83", "+4.297178676e-122", "+8.699490866e-300", "+5.562137865e-57", "+9.063928579e-92", \n "2.743744209e82", "+9.960619645e-39", "-1.962409303e90", "-4.371512402e-287", "4.790326011e-137", \n "+1.295921853e-273", "9.137852847e-96", "2.934099551e35", "-8.176544555e-65", "-7.098452895e-220", \n "+6.665950037e103", "+9.297850239e-254", "-8.529931750e-216", "-9.541329616e-324", "-4.761545594e148", \n "3.507981964e-314", "-3.745430665e-89", "8.799599593e137", "8.736852803e181", "+8.328604940e291", \n "-2.207530122e-202", "-4.259268955e-271", "+1.633874531e-225", "+6.167040542e211", "-2.632062534e-52", \n "-2.296105107e69", "4.935681094e205", "+4.696549581e-117", "+5.032486364e-105", "6.718199716e48",\n "-inf", "Invalid", "nan", "NAN", "snan"\n]\n\nlet float80UniformWorkload = [\n "-4.252484660e-718", "+7.789429046e-2371", "-2.914666745e-2986", "8.287524889e4854", "+4.792668657e-3693", \n "-5.187192176e-756", "+2.452045856e-2309", "+7.133017664e-1055", "-6.749416450e-3803", "+6.808813002e-1771", \n "+7.355881301e3600", "-9.209599679e4848", "+4.142753329e-3268", "3.950199398e-863", "-3.170838470e-4779", \n "9.354087375e718", "2.769339314e-3567", "+1.889983496e3717", "+9.912545495e-2419", "-6.284830753e2041", \n "+9.061812480e3682", "6.551587084e1912", "+6.485690673e-1591", "-3.522511676e-2344", "-6.846303741e-2830", \n "-7.995042826e896", "6.268882688e937", "-3.776199447e-4134", "-2.353057456e801", "5.875638854e-3889", \n "1.245553459e814", "4.593376472e-2139", "-8.277421726e1497", "+1.606488487e1221", "6.433878090e-2220", \n "-2.515502287e2543", "-4.347251565e-1330", "1.101969004e-4525", "-7.602718782e-4037", "-7.289917475e-4547", \n "+1.920523398e2160", "-8.279745071e4493", "+6.383586105e-3771", "-3.784311609e-1828", "-1.193395125e1296", \n "-2.012225848e1954", "+2.238968379e-1455", "6.331805949e-2127", "-7.584066626e-717", "-9.040205012e1614", \n "+1.953864302e4255", "+5.103307458e528", "9.491061048e531", "+2.165292603e54", "-6.471469370e654", \n "-9.275772875e4856", "-4.070772582e1488", "+2.063335882e-2112", "+4.853853159e-3841", "-9.058842001e3955", \n "2.897215261e3511", "1.389094534e-384", "-9.749518987e1602", "+3.103609399e-3559", "-7.156672429e3879",\n "9.385923023e2310", "7.593508637e-2100", "-2.656332678e2833", "6.143253335e-340", "5.794793573e2972", \n "3.869110366e2609", "+2.884288161e-1513", "-5.316488863e4336", "4.948197725e-3829", "3.755250612e-3011", \n "+1.550352355e-767", "-1.625440305e-4354", "+3.086601758e-929", "6.042347288e-357", "-6.176954358e3288", \n "1.594019881e480", "-8.613112966e4863", "+9.864076072e2498", "3.540199292e-821", "+3.770221960e4915", \n "-4.115310178e-3958", "-8.343495037e-4238", "1.165941010e-317", "6.039736339e-693", "6.912425733e1200", \n "-9.307038635e335", "-4.656175810e-637", "-6.342156592e-3848", "-1.221105578e1780", "+6.097066301e-2159", \n "-5.823123345e1389", "+5.404800369e1379", "2.988649766e-736", "-3.733572715e2405", "-1.597565079e-377",\n "+inf", "Invalid", "nan", "NAN", "snan"\n]\n\n@inline(__always)\npublic func parseFloatWorkload<T : LosslessStringConvertible>(_ n: Int, workload: [String], type: T.Type) {\n for _ in 0..<n {\n for element in workload {\n let f = T(element)\n blackHole(f)\n }\n }\n}\n\n@inline(never)\npublic func run_ParseFloatExp(_ n: Int) {\n parseFloatWorkload(n, workload: floatExpWorkload, type: Float.self)\n}\n\n@inline(never)\npublic func run_ParseDoubleExp(_ n: Int) {\n parseFloatWorkload(n, workload: doubleExpWorkload, type: Double.self)\n}\n\n@inline(never)\npublic func run_ParseFloat80Exp(_ n: Int) {\n#if canImport(Darwin) || os(Linux)\n// On Darwin, long double is Float80 on x86, and Double otherwise.\n// On Linux, Float80 is at aleast available on x86.\n#if arch(x86_64) || arch(i386)\n parseFloatWorkload(n, workload: float80ExpWorkload, type: Float80.self)\n#endif // x86\n#endif // Darwin/Linux\n}\n\n@inline(never)\npublic func run_ParseFloatUniform(_ n: Int) {\n parseFloatWorkload(n, workload: floatUniformWorkload, type: Float.self)\n}\n\n@inline(never)\npublic func run_ParseDoubleUniform(_ n: Int) {\n parseFloatWorkload(n, workload: doubleUniformWorkload, type: Double.self)\n}\n\n@inline(never)\npublic func run_ParseFloat80Uniform(_ n: Int) {\n#if canImport(Darwin) || os(Linux)\n// On Darwin, long double is Float80 on x86, and Double otherwise.\n// On Linux, Float80 is at aleast available on x86.\n#if arch(x86_64) || arch(i386)\n parseFloatWorkload(n, workload: float80UniformWorkload, type: Float80.self)\n#endif // x86\n#endif // Darwin/Linux\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_FloatingPointParsing.swift | cpp_apple_swift_benchmark_single-source_FloatingPointParsing.swift | Swift | 15,359 | 0.95 | 0.058608 | 0.204082 | node-utils | 130 | 2024-10-18T22:04:26.836087 | GPL-3.0 | false | 0ec9f3f46d9f3dc6a6a5a873be36511d |
//===--- FloatingPointPrinting.swift -----------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test verifies the performance of generating a text description\n// from a binary floating-point value.\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "FloatingPointPrinting_Float_description_small",\n runFunction: run_FloatingPointPrinting_Float_description_small,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 108),\n\n BenchmarkInfo(\n name: "FloatingPointPrinting_Double_description_small",\n runFunction: run_FloatingPointPrinting_Double_description_small,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 100),\n\n BenchmarkInfo(\n name: "FloatingPointPrinting_Float80_description_small",\n runFunction: run_FloatingPointPrinting_Float80_description_small,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 108),\n\n BenchmarkInfo(\n name: "FloatingPointPrinting_Float_description_uniform",\n runFunction: run_FloatingPointPrinting_Float_description_uniform,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 100),\n\n BenchmarkInfo(\n name: "FloatingPointPrinting_Double_description_uniform",\n runFunction: run_FloatingPointPrinting_Double_description_uniform,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 100),\n\n BenchmarkInfo(\n name: "FloatingPointPrinting_Float80_description_uniform",\n runFunction: run_FloatingPointPrinting_Float80_description_uniform,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 100),\n\n BenchmarkInfo(\n name: "FloatingPointPrinting_Float_interpolated",\n runFunction: run_FloatingPointPrinting_Float_interpolated,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 200),\n\n BenchmarkInfo(\n name: "FloatingPointPrinting_Double_interpolated",\n runFunction: run_FloatingPointPrinting_Double_interpolated,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 200),\n\n BenchmarkInfo(\n name: "FloatingPointPrinting_Float80_interpolated",\n runFunction: run_FloatingPointPrinting_Float80_interpolated,\n tags: [.validation, .api, .runtime, .String],\n legacyFactor: 200)\n]\n\n// Generate descriptions for 100,000 values around 1.0.\n//\n// Note that some formatting algorithms behave very\n// differently for values around 1.0 than they do for\n// less-common extreme values. Having a "small" test\n// and a "uniform" test exercises both cases.\n//\n// Dividing integers 1...100000 by 101 (a prime) yields floating-point\n// values from about 1e-2 to about 1e3, each with plenty of digits after\n// the decimal:\n\n@inline(never)\npublic func run_FloatingPointPrinting_Float_description_small(_ n: Int) {\n let count = 1_000\n for _ in 0..<n {\n for i in 1...count {\n let f = Float(i) / 101.0\n blackHole(f.description)\n }\n }\n}\n\n@inline(never)\npublic func run_FloatingPointPrinting_Double_description_small(_ n: Int) {\n let count = 1_000\n for _ in 0..<n {\n for i in 1...count {\n let f = Double(i) / 101.0\n blackHole(f.description)\n }\n }\n}\n\n@inline(never)\npublic func run_FloatingPointPrinting_Float80_description_small(_ n: Int) {\n#if canImport(Darwin) || os(Linux)\n// On Darwin, long double is Float80 on x86, and Double otherwise.\n// On Linux, Float80 is at aleast available on x86.\n#if arch(x86_64) || arch(i386)\n let count = 1_000\n for _ in 0..<n {\n for i in 1...count {\n let f = Float80(i) / 101.0\n blackHole(f.description)\n }\n }\n#endif // x86\n#endif // Darwin/Linux\n}\n\n// Generate descriptions for 100,000 values spread evenly across\n// the full range of the type:\n\n@inline(never)\npublic func run_FloatingPointPrinting_Float_description_uniform(_ n: Int) {\n let count = 1_000\n let step = UInt32.max / UInt32(count)\n for _ in 0..<n {\n for i in 0..<count {\n let raw = UInt32(i) * step\n let f = Float(bitPattern: raw)\n blackHole(f.description)\n }\n }\n}\n\n@inline(never)\npublic func run_FloatingPointPrinting_Double_description_uniform(_ n: Int) {\n let count = 1_000\n let step = UInt64.max / UInt64(count)\n for _ in 0..<n {\n for i in 0..<count {\n let raw = UInt64(i) * step\n let f = Double(bitPattern: raw)\n blackHole(f.description)\n }\n }\n}\n\n@inline(never)\npublic func run_FloatingPointPrinting_Float80_description_uniform(_ n: Int) {\n#if canImport(Darwin) || os(Linux)\n// On Darwin, long double is Float80 on x86, and Double otherwise.\n// On Linux, Float80 is at aleast available on x86.\n#if arch(x86_64) || arch(i386)\n let count = 1_000\n let step = UInt64.max / UInt64(count)\n for _ in 0..<n {\n for i in 0..<count {\n let fraction = UInt64(i) * step\n let exponent = UInt(i) % 32768\n let f = Float80(sign: .plus, exponentBitPattern: exponent, significandBitPattern: fraction)\n blackHole(f.description)\n }\n }\n#endif // x86\n#endif // Darwin/Linux\n}\n\n// The "interpolated" tests verify that any storage optimizations used while\n// producing the formatted numeric strings don't pessimize later use of the\n// result.\n\n@inline(never)\npublic func run_FloatingPointPrinting_Float_interpolated(_ n: Int) {\n let count = 500\n let step = UInt32.max / UInt32(count)\n for _ in 0..<n {\n for i in 0..<count {\n let raw = UInt32(i) * step\n let f = Float(bitPattern: raw)\n blackHole("and the actual result was \(f)")\n }\n }\n}\n\n@inline(never)\npublic func run_FloatingPointPrinting_Double_interpolated(_ n: Int) {\n let count = 500\n let step = UInt64.max / UInt64(count)\n for _ in 0..<n {\n for i in 0..<count {\n let raw = UInt64(i) * step\n let f = Double(bitPattern: raw)\n blackHole("and the actual result was \(f)")\n }\n }\n}\n\n@inline(never)\npublic func run_FloatingPointPrinting_Float80_interpolated(_ n: Int) {\n#if canImport(Darwin) || os(Linux)\n// On Darwin, long double is Float80 on x86, and Double otherwise.\n// On Linux, Float80 is at aleast available on x86.\n#if arch(x86_64) || arch(i386)\n let count = 500\n let step = UInt64.max / UInt64(count)\n for _ in 0..<n {\n for i in 0..<count {\n let fraction = UInt64(i) * step\n let exponent = UInt(i) % 32768\n let f = Float80(sign: .plus, exponentBitPattern: exponent, significandBitPattern: fraction)\n blackHole("and the actual result was \(f)")\n }\n }\n#endif // x86\n#endif // Darwin/Linux\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_FloatingPointPrinting.swift | cpp_apple_swift_benchmark_single-source_FloatingPointPrinting.swift | Swift | 6,782 | 0.95 | 0.140271 | 0.232323 | node-utils | 263 | 2024-12-04T11:43:04.613028 | MIT | false | fb605525baed1816ac270ed901f04f58 |
//===--- Hanoi.swift ------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance of Swift hanoi tower.\n// <rdar://problem/22151932>\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Hanoi",\n runFunction: run_Hanoi,\n tags: [.validation, .algorithm],\n legacyFactor: 10)\n\nstruct Move {\n var from: String\n var to: String\n init(from:String, to:String) {\n self.from = from\n self.to = to\n }\n}\n\nclass TowersOfHanoi {\n // Record all moves made.\n var moves : [Move] = [Move]()\n\n func solve(_ n: Int, start: String, auxiliary: String, end: String) {\n if (n == 1) {\n moves.append(Move(from:start, to:end))\n } else {\n solve(n - 1, start: start, auxiliary: end, end: auxiliary)\n moves.append(Move(from:start, to:end))\n solve(n - 1, start: auxiliary, auxiliary: start, end: end)\n }\n }\n}\n\n@inline(never)\npublic func run_Hanoi(_ n: Int) {\n for _ in 1...10*n {\n let hanoi: TowersOfHanoi = TowersOfHanoi()\n hanoi.solve(10, start: "A", auxiliary: "B", end: "C")\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Hanoi.swift | cpp_apple_swift_benchmark_single-source_Hanoi.swift | Swift | 1,507 | 0.95 | 0.092593 | 0.291667 | node-utils | 274 | 2024-02-19T20:34:54.628671 | Apache-2.0 | false | caf5ffa18b7d2c4d6fc922c14a5a740c |
//===--- Hash.swift -------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Derived from the C samples in:\n// Source: http://en.wikipedia.org/wiki/MD5 and\n// http://en.wikipedia.org/wiki/SHA-1\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "HashTest",\n runFunction: run_HashTest,\n tags: [.validation, .algorithm],\n legacyFactor: 10),\n]\n\nclass Hash {\n /// C'tor.\n init(_ bs: Int) {\n blocksize = bs\n messageLength = 0\n dataLength = 0\n assert(blocksize <= 64, "Invalid block size")\n }\n\n /// Add the bytes in \p Msg to the hash.\n func update(_ Msg: String) {\n for c in Msg.unicodeScalars {\n data[dataLength] = UInt8(ascii: c)\n dataLength += 1\n messageLength += 1\n if dataLength == blocksize { hash() }\n }\n }\n\n /// Add the bytes in \p Msg to the hash.\n func update(_ Msg: [UInt8]) {\n for c in Msg {\n data[dataLength] = c\n dataLength += 1\n messageLength += 1\n if dataLength == blocksize { hash() }\n }\n }\n\n /// \returns the hash of the data that was updated.\n func digest() -> String {\n fillBlock()\n hash()\n let x = hashState()\n return x\n }\n\n // private:\n\n // Hash state:\n final var messageLength: Int = 0\n final var dataLength: Int = 0\n final var data = [UInt8](repeating: 0, count: 64)\n final var blocksize: Int\n\n /// Hash the internal data.\n func hash() {\n fatalError("Pure virtual")\n }\n\n /// \returns a string representation of the state.\n func hashState() -> String {\n fatalError("Pure virtual")\n }\n func hashStateFast(_ res: inout [UInt8]) {\n fatalError("Pure virtual")\n }\n\n /// Blow the data to fill the block.\n func fillBlock() {\n fatalError("Pure virtual")\n }\n\n var hexTable = ["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]\n final\n var hexTableFast : [UInt8] = [48,49,50,51,52,53,54,55,56,57,97,98,99,100,101,102]\n\n /// Convert a 4-byte integer to a hex string.\n final\n func toHex(_ input: UInt32) -> String {\n var input = input\n var res = ""\n for _ in 0..<8 {\n res = hexTable[Int(input & 0xF)] + res\n input = input >> 4\n }\n return res\n }\n\n final\n func toHexFast(_ input: UInt32, _ res: inout Array<UInt8>, _ index : Int) {\n var input = input\n for i in 0..<4 {\n // Convert one byte each iteration.\n res[index + 2*i] = hexTableFast[Int(input >> 4) & 0xF]\n res[index + 2*i + 1] = hexTableFast[Int(input & 0xF)]\n input = input >> 8\n }\n }\n\n /// Left-rotate \p x by \p c.\n final\n func rol(_ x: UInt32, _ c: UInt32) -> UInt32 {\n return x &<< c | x &>> (32 &- c)\n }\n\n /// Right-rotate \p x by \p c.\n final\n func ror(_ x: UInt32, _ c: UInt32) -> UInt32 {\n return x &>> c | x &<< (32 &- c)\n }\n}\n\nfinal\nclass MD5 : Hash {\n // Integer part of the sines of integers (in radians) * 2^32.\n let k : [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee ,\n 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501 ,\n 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be ,\n 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 ,\n 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa ,\n 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8 ,\n 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed ,\n 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a ,\n 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c ,\n 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70 ,\n 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05 ,\n 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 ,\n 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039 ,\n 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1 ,\n 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1 ,\n 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 ]\n\n // Per-round shift amounts\n let r : [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,\n 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,\n 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,\n 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]\n\n // State\n var h0: UInt32 = 0\n var h1: UInt32 = 0\n var h2: UInt32 = 0\n var h3: UInt32 = 0\n\n init() {\n super.init(64)\n reset()\n }\n\n func reset() {\n // Set the initial values.\n h0 = 0x67452301\n h1 = 0xefcdab89\n h2 = 0x98badcfe\n h3 = 0x10325476\n messageLength = 0\n dataLength = 0\n }\n\n func appendBytes(_ val: Int, _ message: inout Array<UInt8>, _ offset : Int) {\n message[offset] = UInt8(truncatingIfNeeded: val)\n message[offset + 1] = UInt8(truncatingIfNeeded: val >> 8)\n message[offset + 2] = UInt8(truncatingIfNeeded: val >> 16)\n message[offset + 3] = UInt8(truncatingIfNeeded: val >> 24)\n }\n\n override\n func fillBlock() {\n // Pre-processing:\n // Append "1" bit to message\n // Append "0" bits until message length in bits -> 448 (mod 512)\n // Append length mod (2^64) to message\n\n var new_len = messageLength + 1\n while (new_len % (512/8) != 448/8) {\n new_len += 1\n }\n\n // Append the "1" bit - most significant bit is "first"\n data[dataLength] = UInt8(0x80)\n dataLength += 1\n\n // Append "0" bits\n for _ in 0..<(new_len - (messageLength + 1)) {\n if dataLength == blocksize { hash() }\n data[dataLength] = UInt8(0)\n dataLength += 1\n }\n\n // Append the len in bits at the end of the buffer.\n // initial_len>>29 == initial_len*8>>32, but avoids overflow.\n appendBytes(messageLength * 8, &data, dataLength)\n appendBytes(messageLength>>29 * 8, &data, dataLength+4)\n dataLength += 8\n }\n\n func toUInt32(_ message: Array<UInt8>, _ offset: Int) -> UInt32 {\n let first = UInt32(message[offset + 0])\n let second = UInt32(message[offset + 1]) << 8\n let third = UInt32(message[offset + 2]) << 16\n let fourth = UInt32(message[offset + 3]) << 24\n return first | second | third | fourth\n }\n\n var w = [UInt32](repeating: 0, count: 16)\n override\n func hash() {\n assert(dataLength == blocksize, "Invalid block size")\n\n // Break chunk into sixteen 32-bit words w[j], 0 ≤ j ≤ 15\n for i in 0..<16 {\n w[i] = toUInt32(data, i*4)\n }\n\n // We don't need the original data anymore.\n dataLength = 0\n\n var a = h0\n var b = h1\n var c = h2\n var d = h3\n var f, g: UInt32\n\n // Main loop:\n for i in 0..<64 {\n if i < 16 {\n f = (b & c) | ((~b) & d)\n g = UInt32(i)\n } else if i < 32 {\n f = (d & b) | ((~d) & c)\n g = UInt32(5*i + 1) % 16\n } else if i < 48 {\n f = b ^ c ^ d\n g = UInt32(3*i + 5) % 16\n } else {\n f = c ^ (b | (~d))\n g = UInt32(7*i) % 16\n }\n\n let temp = d\n d = c\n c = b\n b = b &+ rol(a &+ f &+ k[i] &+ w[Int(g)], r[i])\n a = temp\n }\n\n // Add this chunk's hash to result so far:\n h0 = a &+ h0\n h1 = b &+ h1\n h2 = c &+ h2\n h3 = d &+ h3\n }\n\n func reverseBytes(_ input: UInt32) -> UInt32 {\n let b0 = (input >> 0 ) & 0xFF\n let b1 = (input >> 8 ) & 0xFF\n let b2 = (input >> 16) & 0xFF\n let b3 = (input >> 24) & 0xFF\n return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3\n }\n\n override\n func hashState() -> String {\n var s = ""\n for h in [h0, h1, h2, h3] {\n s += toHex(reverseBytes(h))\n }\n return s\n }\n\n override\n func hashStateFast(_ res: inout [UInt8]) {\n#if !NO_RANGE\n var idx: Int = 0\n for h in [h0, h1, h2, h3] {\n toHexFast(h, &res, idx)\n idx += 8\n }\n#else\n toHexFast(h0, &res, 0)\n toHexFast(h1, &res, 8)\n toHexFast(h2, &res, 16)\n toHexFast(h3, &res, 24)\n#endif\n }\n\n}\n\nclass SHA1 : Hash {\n // State\n var h0: UInt32 = 0\n var h1: UInt32 = 0\n var h2: UInt32 = 0\n var h3: UInt32 = 0\n var h4: UInt32 = 0\n\n init() {\n super.init(64)\n reset()\n }\n\n func reset() {\n // Set the initial values.\n h0 = 0x67452301\n h1 = 0xEFCDAB89\n h2 = 0x98BADCFE\n h3 = 0x10325476\n h4 = 0xC3D2E1F0\n messageLength = 0\n dataLength = 0\n }\n\n override\n func fillBlock() {\n // Append a 1 to the message.\n data[dataLength] = UInt8(0x80)\n dataLength += 1\n\n var new_len = messageLength + 1\n while ((new_len % 64) != 56) {\n new_len += 1\n }\n\n for _ in 0..<new_len - (messageLength + 1) {\n if dataLength == blocksize { hash() }\n data[dataLength] = UInt8(0x0)\n dataLength += 1\n }\n\n // Append the original message length as 64bit big endian:\n let len_in_bits = Int64(messageLength)*8\n for i in 0..<(8 as Int64) {\n let val = (len_in_bits >> ((7-i)*8)) & 0xFF\n data[dataLength] = UInt8(val)\n dataLength += 1\n }\n }\n\n override\n func hash() {\n assert(dataLength == blocksize, "Invalid block size")\n\n // Init the "W" buffer.\n var w = [UInt32](repeating: 0, count: 80)\n\n // Convert the Byte array to UInt32 array.\n var word: UInt32 = 0\n for i in 0..<64 {\n word = word << 8\n word = word &+ UInt32(data[i])\n if i%4 == 3 { w[i/4] = word; word = 0 }\n }\n\n // Init the rest of the "W" buffer.\n for t in 16..<80 {\n // splitting into 2 subexpressions to help typechecker\n let lhs = w[t-3] ^ w[t-8]\n let rhs = w[t-14] ^ w[t-16]\n w[t] = rol(lhs ^ rhs, 1)\n }\n\n dataLength = 0\n\n var a = h0\n var b = h1\n var c = h2\n var d = h3\n var e = h4\n var k: UInt32, f: UInt32\n\n for t in 0..<80 {\n if t < 20 {\n k = 0x5a827999\n f = (b & c) | ((b ^ 0xFFFFFFFF) & d)\n } else if t < 40 {\n k = 0x6ed9eba1\n f = b ^ c ^ d\n } else if t < 60 {\n k = 0x8f1bbcdc\n f = (b & c) | (b & d) | (c & d)\n } else {\n k = 0xca62c1d6\n f = b ^ c ^ d\n }\n let temp: UInt32 = rol(a,5) &+ f &+ e &+ w[t] &+ k\n\n e = d\n d = c\n c = rol(b,30)\n b = a\n a = temp\n }\n\n h0 = h0 &+ a\n h1 = h1 &+ b\n h2 = h2 &+ c\n h3 = h3 &+ d\n h4 = h4 &+ e\n }\n\n override\n func hashState() -> String {\n var res: String = ""\n for state in [h0, h1, h2, h3, h4] {\n res += toHex(state)\n }\n return res\n }\n}\n\nclass SHA256 : Hash {\n // State\n var h0: UInt32 = 0\n var h1: UInt32 = 0\n var h2: UInt32 = 0\n var h3: UInt32 = 0\n var h4: UInt32 = 0\n var h5: UInt32 = 0\n var h6: UInt32 = 0\n var h7: UInt32 = 0\n\n let k : [UInt32] = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]\n\n init() {\n super.init(64)\n reset()\n }\n\n func reset() {\n // Set the initial values.\n h0 = 0x6a09e667\n h1 = 0xbb67ae85\n h2 = 0x3c6ef372\n h3 = 0xa54ff53a\n h4 = 0x510e527f\n h5 = 0x9b05688c\n h6 = 0x1f83d9ab\n h7 = 0x5be0cd19\n messageLength = 0\n dataLength = 0\n }\n\n override\n func fillBlock() {\n // Append a 1 to the message.\n data[dataLength] = UInt8(0x80)\n dataLength += 1\n\n var new_len = messageLength + 1\n while ((new_len % 64) != 56) {\n new_len += 1\n }\n\n for _ in 0..<new_len - (messageLength+1) {\n if dataLength == blocksize { hash() }\n data[dataLength] = UInt8(0)\n dataLength += 1\n }\n\n // Append the original message length as 64bit big endian:\n let len_in_bits = Int64(messageLength)*8\n for i in 0..<(8 as Int64) {\n let val = (len_in_bits >> ((7-i)*8)) & 0xFF\n data[dataLength] = UInt8(val)\n dataLength += 1\n }\n }\n\n override\n func hash() {\n assert(dataLength == blocksize, "Invalid block size")\n\n // Init the "W" buffer.\n var w = [UInt32](repeating: 0, count: 64)\n\n // Convert the Byte array to UInt32 array.\n var word: UInt32 = 0\n for i in 0..<64 {\n word = word << 8\n word = word &+ UInt32(data[i])\n if i%4 == 3 { w[i/4] = word; word = 0 }\n }\n\n // Init the rest of the "W" buffer.\n for i in 16..<64 {\n let s0 = ror(w[i-15], 7) ^ ror(w[i-15], 18) ^ (w[i-15] >> 3)\n let s1 = ror(w[i-2], 17) ^ ror(w[i-2], 19) ^ (w[i-2] >> 10)\n w[i] = w[i-16] &+ s0 &+ w[i-7] &+ s1\n }\n\n dataLength = 0\n\n var a = h0\n var b = h1\n var c = h2\n var d = h3\n var e = h4\n var f = h5\n var g = h6\n var h = h7\n\n for i in 0..<64 {\n let s1 = ror(e, 6) ^ ror(e, 11) ^ ror(e, 25)\n let ch = (e & f) ^ ((~e) & g)\n let temp1 = h &+ s1 &+ ch &+ k[i] &+ w[i]\n let s0 = ror(a, 2) ^ ror(a, 13) ^ ror(a, 22)\n let maj = (a & b) ^ (a & c) ^ (b & c)\n let temp2 = s0 &+ maj\n\n h = g\n g = f\n f = e\n e = d &+ temp1\n d = c\n c = b\n b = a\n a = temp1 &+ temp2\n }\n\n h0 = h0 &+ a\n h1 = h1 &+ b\n h2 = h2 &+ c\n h3 = h3 &+ d\n h4 = h4 &+ e\n h5 = h5 &+ f\n h6 = h6 &+ g\n h7 = h7 &+ h\n }\n\n override\n func hashState() -> String {\n var res: String = ""\n for state in [h0, h1, h2, h3, h4, h5, h6, h7] {\n res += toHex(state)\n }\n return res\n }\n}\n\nfunc == (lhs: [UInt8], rhs: [UInt8]) -> Bool {\n if lhs.count != rhs.count { return false }\n for idx in 0..<lhs.count {\n if lhs[idx] != rhs[idx] { return false }\n }\n return true\n}\n\n@inline(never)\npublic func run_HashTest(_ n: Int) {\n let testMD5 = ["" : "d41d8cd98f00b204e9800998ecf8427e",\n "The quick brown fox jumps over the lazy dog." : "e4d909c290d0fb1ca068ffaddf22cbd0",\n "The quick brown fox jumps over the lazy cog." : "68aa5deab43e4df2b5e1f80190477fb0"]\n\n let testSHA1 = ["" : "da39a3ee5e6b4b0d3255bfef95601890afd80709",\n "The quick brown fox jumps over the lazy dog" : "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12",\n "The quick brown fox jumps over the lazy cog" : "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3"]\n\n let testSHA256 = ["" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",\n "The quick brown fox jumps over the lazy dog" : "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592",\n "The quick brown fox jumps over the lazy dog." : "ef537f25c895bfa782526529a9b63d97aa631564d5d789c2b765448c8635fb6c"]\n let size = 50\n\n for _ in 1...n {\n // Check for precomputed values.\n let md = MD5()\n for (k, v) in testMD5 {\n md.update(k)\n check(md.digest() == v)\n md.reset()\n }\n\n // Check that we don't crash on large strings.\n var s: String = ""\n for _ in 1...size {\n s += "a"\n md.reset()\n md.update(s)\n }\n\n // Check that the order in which we push values does not change the result.\n md.reset()\n var l: String = ""\n for _ in 1...size {\n l += "a"\n md.update("a")\n }\n let md2 = MD5()\n md2.update(l)\n check(md.digest() == md2.digest())\n\n // Test the famous md5 collision from 2009: http://www.mscs.dal.ca/~selinger/md5collision/\n let src1 : [UInt8] =\n [0xd1, 0x31, 0xdd, 0x02, 0xc5, 0xe6, 0xee, 0xc4, 0x69, 0x3d, 0x9a, 0x06, 0x98, 0xaf, 0xf9, 0x5c, 0x2f, 0xca, 0xb5, 0x87, 0x12, 0x46, 0x7e, 0xab, 0x40, 0x04, 0x58, 0x3e, 0xb8, 0xfb, 0x7f, 0x89,\n 0x55, 0xad, 0x34, 0x06, 0x09, 0xf4, 0xb3, 0x02, 0x83, 0xe4, 0x88, 0x83, 0x25, 0x71, 0x41, 0x5a, 0x08, 0x51, 0x25, 0xe8, 0xf7, 0xcd, 0xc9, 0x9f, 0xd9, 0x1d, 0xbd, 0xf2, 0x80, 0x37, 0x3c, 0x5b,\n 0xd8, 0x82, 0x3e, 0x31, 0x56, 0x34, 0x8f, 0x5b, 0xae, 0x6d, 0xac, 0xd4, 0x36, 0xc9, 0x19, 0xc6, 0xdd, 0x53, 0xe2, 0xb4, 0x87, 0xda, 0x03, 0xfd, 0x02, 0x39, 0x63, 0x06, 0xd2, 0x48, 0xcd, 0xa0,\n 0xe9, 0x9f, 0x33, 0x42, 0x0f, 0x57, 0x7e, 0xe8, 0xce, 0x54, 0xb6, 0x70, 0x80, 0xa8, 0x0d, 0x1e, 0xc6, 0x98, 0x21, 0xbc, 0xb6, 0xa8, 0x83, 0x93, 0x96, 0xf9, 0x65, 0x2b, 0x6f, 0xf7, 0x2a, 0x70]\n\n let src2 : [UInt8] =\n [0xd1, 0x31, 0xdd, 0x02, 0xc5, 0xe6, 0xee, 0xc4, 0x69, 0x3d, 0x9a, 0x06, 0x98, 0xaf, 0xf9, 0x5c, 0x2f, 0xca, 0xb5, 0x07, 0x12, 0x46, 0x7e, 0xab, 0x40, 0x04, 0x58, 0x3e, 0xb8, 0xfb, 0x7f, 0x89,\n 0x55, 0xad, 0x34, 0x06, 0x09, 0xf4, 0xb3, 0x02, 0x83, 0xe4, 0x88, 0x83, 0x25, 0xf1, 0x41, 0x5a, 0x08, 0x51, 0x25, 0xe8, 0xf7, 0xcd, 0xc9, 0x9f, 0xd9, 0x1d, 0xbd, 0x72, 0x80, 0x37, 0x3c, 0x5b,\n 0xd8, 0x82, 0x3e, 0x31, 0x56, 0x34, 0x8f, 0x5b, 0xae, 0x6d, 0xac, 0xd4, 0x36, 0xc9, 0x19, 0xc6, 0xdd, 0x53, 0xe2, 0x34, 0x87, 0xda, 0x03, 0xfd, 0x02, 0x39, 0x63, 0x06, 0xd2, 0x48, 0xcd, 0xa0,\n 0xe9, 0x9f, 0x33, 0x42, 0x0f, 0x57, 0x7e, 0xe8, 0xce, 0x54, 0xb6, 0x70, 0x80, 0x28, 0x0d, 0x1e, 0xc6, 0x98, 0x21, 0xbc, 0xb6, 0xa8, 0x83, 0x93, 0x96, 0xf9, 0x65, 0xab, 0x6f, 0xf7, 0x2a, 0x70]\n\n let h1 = MD5()\n let h2 = MD5()\n\n h1.update(src1)\n h2.update(src2)\n let a1 = h1.digest()\n let a2 = h2.digest()\n check(a1 == a2)\n check(a1 == "79054025255fb1a26e4bc422aef54eb4")\n h1.reset()\n h2.reset()\n\n let sh = SHA1()\n let sh256 = SHA256()\n for (k, v) in testSHA1 {\n sh.update(k)\n check(sh.digest() == v)\n sh.reset()\n }\n\n for (k, v) in testSHA256 {\n sh256.update(k)\n check(sh256.digest() == v)\n sh256.reset()\n }\n\n // Check that we don't crash on large strings.\n s = ""\n for _ in 1...size {\n s += "a"\n sh.reset()\n sh.update(s)\n }\n\n // Check that the order in which we push values does not change the result.\n sh.reset()\n l = ""\n for _ in 1...size {\n l += "a"\n sh.update("a")\n }\n let sh2 = SHA1()\n sh2.update(l)\n check(sh.digest() == sh2.digest())\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Hash.swift | cpp_apple_swift_benchmark_single-source_Hash.swift | Swift | 18,579 | 0.95 | 0.08321 | 0.114726 | python-kit | 53 | 2024-09-14T15:39:18.431888 | BSD-3-Clause | false | b1f32c6546cad4c3f1de2fde2fa5d063 |
//===--- Histogram.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test measures performance of histogram generating.\n// <rdar://problem/17384894>\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Histogram",\n runFunction: run_Histogram,\n tags: [.validation, .algorithm])\n\ntypealias rrggbb_t = UInt32\n\nfunc output_sorted_sparse_rgb_histogram<S: Sequence>(_ samples: S, _ n: Int)\n where S.Element == rrggbb_t {\n var histogram = Dictionary<rrggbb_t, Int>()\n for _ in 1...50*n {\n for sample in samples { // This part is really awful, I agree\n let i = histogram.index(forKey: sample)\n histogram[sample] = (i != nil ? histogram[i!].1 : 0) + 1\n }\n }\n}\n\n// Packed-RGB test data: four gray samples, two red, two blue, and a 4 pixel gradient from black to white\nlet samples: [rrggbb_t] = [\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF\n]\n\n@inline(never)\npublic func run_Histogram(_ n: Int) {\n output_sorted_sparse_rgb_histogram(samples, n)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Histogram.swift | cpp_apple_swift_benchmark_single-source_Histogram.swift | Swift | 5,298 | 0.95 | 0.033058 | 0.121739 | node-utils | 433 | 2025-04-29T18:15:12.648444 | GPL-3.0 | false | b001f08ca0c4fc667d4f66d55c53f5e1 |
//===--- HTTP2StateMachine.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n//\n// A trimmed-down version of SwiftNIO's HTTP/2 stream state machine. This version removes all code\n// comments and removes any custom data types that are used by SwiftNIO. Its purpose is to benchmark\n// Swift's performance switching over enums with substantial amounts of associated data.\n//\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "HTTP2StateMachine",\n runFunction: run_HTTP2StateMachine,\n tags: [.miniapplication])\n]\n\ntypealias HTTP2FlowControlWindow = Int\n\n\nstruct HTTP2StreamStateMachine {\n enum State {\n case idle(localRole: StreamRole, localWindow: HTTP2FlowControlWindow, remoteWindow: HTTP2FlowControlWindow)\n case reservedRemote(remoteWindow: HTTP2FlowControlWindow)\n case reservedLocal(localWindow: HTTP2FlowControlWindow)\n case halfOpenLocalPeerIdle(localWindow: HTTP2FlowControlWindow, remoteWindow: HTTP2FlowControlWindow)\n case halfOpenRemoteLocalIdle(localWindow: HTTP2FlowControlWindow, remoteWindow: HTTP2FlowControlWindow)\n case fullyOpen(localRole: StreamRole, localWindow: HTTP2FlowControlWindow, remoteWindow: HTTP2FlowControlWindow)\n case halfClosedLocalPeerIdle(remoteWindow: HTTP2FlowControlWindow)\n case halfClosedLocalPeerActive(localRole: StreamRole, initiatedBy: StreamRole, remoteWindow: HTTP2FlowControlWindow)\n case halfClosedRemoteLocalIdle(localWindow: HTTP2FlowControlWindow)\n case halfClosedRemoteLocalActive(localRole: StreamRole, initiatedBy: StreamRole, localWindow: HTTP2FlowControlWindow)\n case closed\n }\n\n enum StreamRole {\n case server\n case client\n }\n\n private var state: State\n\n init(localRole: StreamRole, localWindow: HTTP2FlowControlWindow, remoteWindow: HTTP2FlowControlWindow) {\n self.state = .idle(localRole: localRole, localWindow: localWindow, remoteWindow: remoteWindow)\n }\n\n init(receivedPushPromiseWithRemoteInitialWindowSize remoteWindow: HTTP2FlowControlWindow) {\n self.state = .reservedRemote(remoteWindow: remoteWindow)\n }\n\n init(sentPushPromiseWithLocalInitialWindowSize localWindow: HTTP2FlowControlWindow) {\n self.state = .reservedLocal(localWindow: localWindow)\n }\n\n @inline(never)\n mutating func sendHeaders(isEndStreamSet endStream: Bool) -> Bool {\n switch self.state {\n case .idle(.client, localWindow: let localWindow, remoteWindow: let remoteWindow):\n self.state = endStream ? .halfClosedLocalPeerIdle(remoteWindow: remoteWindow) : .halfOpenLocalPeerIdle(localWindow: localWindow, remoteWindow: remoteWindow)\n return true\n\n case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteWindow: let remoteWindow):\n self.state = endStream ? .halfClosedLocalPeerActive(localRole: .server, initiatedBy: .client, remoteWindow: remoteWindow) : .fullyOpen(localRole: .server, localWindow: localWindow, remoteWindow: remoteWindow)\n return true\n\n case .halfOpenLocalPeerIdle(localWindow: _, remoteWindow: let remoteWindow):\n self.state = .halfClosedLocalPeerIdle(remoteWindow: remoteWindow)\n return true\n\n case .reservedLocal(let localWindow):\n self.state = endStream ? .closed : .halfClosedRemoteLocalActive(localRole: .server, initiatedBy: .server, localWindow: localWindow)\n return true\n\n case .fullyOpen(let localRole, localWindow: _, remoteWindow: let remoteWindow):\n self.state = .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: .client, remoteWindow: remoteWindow)\n return true\n\n case .halfClosedRemoteLocalIdle(let localWindow):\n self.state = endStream ? .closed : . halfClosedRemoteLocalActive(localRole: .server, initiatedBy: .client, localWindow: localWindow)\n return true\n\n case .halfClosedRemoteLocalActive:\n self.state = .closed\n return true\n\n\n case .idle(.server, _, _), .closed:\n return false\n\n case .reservedRemote, .halfClosedLocalPeerIdle, .halfClosedLocalPeerActive:\n return false\n }\n }\n\n @inline(never)\n mutating func receiveHeaders(isEndStreamSet endStream: Bool) -> Bool {\n switch self.state {\n case .idle(.server, localWindow: let localWindow, remoteWindow: let remoteWindow):\n self.state = endStream ? .halfClosedRemoteLocalIdle(localWindow: localWindow) : .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteWindow: remoteWindow)\n return true\n\n case .halfOpenLocalPeerIdle(localWindow: let localWindow, remoteWindow: let remoteWindow):\n self.state = endStream ? .halfClosedRemoteLocalActive(localRole: .client,initiatedBy: .client, localWindow: localWindow) : .fullyOpen(localRole: .client, localWindow: localWindow, remoteWindow: remoteWindow)\n return true\n\n case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteWindow: _):\n self.state = .halfClosedRemoteLocalIdle(localWindow: localWindow)\n return true\n\n case .reservedRemote(let remoteWindow):\n self.state = endStream ? .closed : .halfClosedLocalPeerActive(localRole: .client, initiatedBy: .server, remoteWindow: remoteWindow)\n return true\n\n case .fullyOpen(let localRole, localWindow: let localWindow, remoteWindow: _):\n self.state = .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: .client, localWindow: localWindow)\n return true\n\n case .halfClosedLocalPeerIdle(let remoteWindow):\n self.state = endStream ? .closed : . halfClosedLocalPeerActive(localRole: .client, initiatedBy: .client, remoteWindow: remoteWindow)\n return true\n\n case .halfClosedLocalPeerActive:\n self.state = .closed\n return true\n\n case .idle(.client, _, _), .closed:\n return false\n\n case .reservedLocal, .halfClosedRemoteLocalIdle, .halfClosedRemoteLocalActive:\n return false\n }\n }\n\n @inline(never)\n mutating func sendData(flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> Bool {\n switch self.state {\n case .halfOpenLocalPeerIdle(localWindow: var localWindow, remoteWindow: let remoteWindow):\n localWindow -= flowControlledBytes\n self.state = endStream ? .halfClosedLocalPeerIdle(remoteWindow: remoteWindow) : .halfOpenLocalPeerIdle(localWindow: localWindow, remoteWindow: remoteWindow)\n return true\n\n case .fullyOpen(let localRole, localWindow: var localWindow, remoteWindow: let remoteWindow):\n localWindow -= flowControlledBytes\n self.state = endStream ? .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: .client, remoteWindow: remoteWindow) : .fullyOpen(localRole: localRole, localWindow: localWindow, remoteWindow: remoteWindow)\n return true\n\n case .halfClosedRemoteLocalActive(let localRole, let initiatedBy, var localWindow):\n localWindow -= flowControlledBytes\n self.state = endStream ? .closed : .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: initiatedBy, localWindow: localWindow)\n return true\n\n case .idle, .halfOpenRemoteLocalIdle, .reservedLocal, .reservedRemote, .halfClosedLocalPeerIdle,\n .halfClosedLocalPeerActive, .halfClosedRemoteLocalIdle, .closed:\n return false\n }\n }\n\n @inline(never)\n mutating func receiveData(flowControlledBytes: Int, isEndStreamSet endStream: Bool) -> Bool {\n switch self.state {\n case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteWindow: var remoteWindow):\n remoteWindow -= flowControlledBytes\n self.state = endStream ? .halfClosedRemoteLocalIdle(localWindow: localWindow) : .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteWindow: remoteWindow)\n return true\n\n case .fullyOpen(let localRole, localWindow: let localWindow, remoteWindow: var remoteWindow):\n remoteWindow -= flowControlledBytes\n self.state = endStream ? .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: .client, localWindow: localWindow) : .fullyOpen(localRole: localRole, localWindow: localWindow, remoteWindow: remoteWindow)\n return true\n\n case .halfClosedLocalPeerActive(let localRole, let initiatedBy, var remoteWindow):\n remoteWindow -= flowControlledBytes\n self.state = endStream ? .closed : .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: initiatedBy, remoteWindow: remoteWindow)\n return true\n\n case .idle, .halfOpenLocalPeerIdle, .reservedLocal, .reservedRemote, .halfClosedLocalPeerIdle,\n .halfClosedRemoteLocalActive, .halfClosedRemoteLocalIdle, .closed:\n return false\n }\n }\n\n @inline(never)\n mutating func sendPushPromise() -> Bool {\n switch self.state {\n case .fullyOpen(localRole: .server, localWindow: _, remoteWindow: _),\n .halfClosedRemoteLocalActive(localRole: .server, initiatedBy: .client, localWindow: _):\n return true\n\n case .idle, .reservedLocal, .reservedRemote, .halfClosedLocalPeerIdle, .halfClosedLocalPeerActive,\n .halfClosedRemoteLocalIdle, .halfOpenLocalPeerIdle, .halfOpenRemoteLocalIdle, .closed,\n .fullyOpen(localRole: .client, localWindow: _, remoteWindow: _),\n .halfClosedRemoteLocalActive(localRole: .client, initiatedBy: _, localWindow: _),\n .halfClosedRemoteLocalActive(localRole: .server, initiatedBy: .server, localWindow: _):\n return false\n }\n }\n\n @inline(never)\n mutating func receivePushPromise() -> Bool {\n switch self.state {\n case .fullyOpen(localRole: .client, localWindow: _, remoteWindow: _),\n .halfClosedLocalPeerActive(localRole: .client, initiatedBy: .client, remoteWindow: _):\n return true\n\n case .idle, .reservedLocal, .reservedRemote, .halfClosedLocalPeerIdle, .halfClosedRemoteLocalIdle,\n .halfClosedRemoteLocalActive, .halfOpenLocalPeerIdle, .halfOpenRemoteLocalIdle, .closed,\n .fullyOpen(localRole: .server, localWindow: _, remoteWindow: _),\n .halfClosedLocalPeerActive(localRole: .server, initiatedBy: _, remoteWindow: _),\n .halfClosedLocalPeerActive(localRole: .client, initiatedBy: .server, remoteWindow: _):\n return false\n }\n }\n\n @inline(never)\n mutating func sendWindowUpdate(windowIncrement: Int) -> Bool {\n switch self.state {\n case .reservedRemote(remoteWindow: var remoteWindow):\n remoteWindow += windowIncrement\n self.state = .reservedRemote(remoteWindow: remoteWindow)\n\n case .halfOpenLocalPeerIdle(localWindow: let localWindow, remoteWindow: var remoteWindow):\n remoteWindow += windowIncrement\n self.state = .halfOpenLocalPeerIdle(localWindow: localWindow, remoteWindow: remoteWindow)\n\n case .halfOpenRemoteLocalIdle(localWindow: let localWindow, remoteWindow: var remoteWindow):\n remoteWindow += windowIncrement\n self.state = .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteWindow: remoteWindow)\n\n case .fullyOpen(localRole: let localRole, localWindow: let localWindow, remoteWindow: var remoteWindow):\n remoteWindow += windowIncrement\n self.state = .fullyOpen(localRole: localRole, localWindow: localWindow, remoteWindow: remoteWindow)\n\n case .halfClosedLocalPeerIdle(remoteWindow: var remoteWindow):\n remoteWindow += windowIncrement\n self.state = .halfClosedLocalPeerIdle(remoteWindow: remoteWindow)\n\n case .halfClosedLocalPeerActive(localRole: let localRole, initiatedBy: let initiatedBy, remoteWindow: var remoteWindow):\n remoteWindow += windowIncrement\n self.state = .halfClosedLocalPeerActive(localRole: localRole, initiatedBy: initiatedBy, remoteWindow: remoteWindow)\n\n case .idle, .reservedLocal, .halfClosedRemoteLocalIdle, .halfClosedRemoteLocalActive, .closed:\n return false\n }\n\n return true\n }\n\n @inline(never)\n mutating func receiveWindowUpdate(windowIncrement: Int) -> Bool {\n switch self.state {\n case .reservedLocal(localWindow: var localWindow):\n localWindow += windowIncrement\n self.state = .reservedLocal(localWindow: localWindow)\n\n case .halfOpenLocalPeerIdle(localWindow: var localWindow, remoteWindow: let remoteWindow):\n localWindow += windowIncrement\n self.state = .halfOpenLocalPeerIdle(localWindow: localWindow, remoteWindow: remoteWindow)\n\n case .halfOpenRemoteLocalIdle(localWindow: var localWindow, remoteWindow: let remoteWindow):\n localWindow += windowIncrement\n self.state = .halfOpenRemoteLocalIdle(localWindow: localWindow, remoteWindow: remoteWindow)\n\n case .fullyOpen(localRole: let localRole, localWindow: var localWindow, remoteWindow: let remoteWindow):\n localWindow += windowIncrement\n self.state = .fullyOpen(localRole: localRole, localWindow: localWindow, remoteWindow: remoteWindow)\n\n case .halfClosedRemoteLocalIdle(localWindow: var localWindow):\n localWindow += windowIncrement\n self.state = .halfClosedRemoteLocalIdle(localWindow: localWindow)\n\n case .halfClosedRemoteLocalActive(localRole: let localRole, initiatedBy: let initiatedBy, localWindow: var localWindow):\n localWindow += windowIncrement\n self.state = .halfClosedRemoteLocalActive(localRole: localRole, initiatedBy: initiatedBy, localWindow: localWindow)\n\n case .halfClosedLocalPeerIdle, .halfClosedLocalPeerActive:\n break\n\n case .idle, .reservedRemote, .closed:\n return false\n }\n\n return true\n }\n}\n\n@inline(never)\nfunc testSimpleRequestResponse(_ n: Int) -> Bool {\n var successful = true\n\n var server = HTTP2StreamStateMachine(localRole: .server, localWindow: 1<<16, remoteWindow: n)\n var client = HTTP2StreamStateMachine(localRole: .client, localWindow: 1<<16, remoteWindow: n)\n\n successful = successful && client.sendHeaders(isEndStreamSet: false)\n successful = successful && server.receiveHeaders(isEndStreamSet: false)\n\n successful = successful && client.sendData(flowControlledBytes: 128, isEndStreamSet: false)\n successful = successful && client.sendData(flowControlledBytes: 128, isEndStreamSet: false)\n successful = successful && server.receiveData(flowControlledBytes: 128, isEndStreamSet: false)\n successful = successful && server.receiveData(flowControlledBytes: 128, isEndStreamSet: false)\n\n successful = successful && server.sendWindowUpdate(windowIncrement: 256)\n successful = successful && client.receiveWindowUpdate(windowIncrement: 256)\n\n successful = successful && client.sendData(flowControlledBytes: 128, isEndStreamSet: true)\n successful = successful && server.receiveData(flowControlledBytes: 128, isEndStreamSet: true)\n\n successful = successful && server.sendHeaders(isEndStreamSet: false)\n successful = successful && client.receiveHeaders(isEndStreamSet: false)\n\n successful = successful && server.sendData(flowControlledBytes: 1024, isEndStreamSet: false)\n successful = successful && client.receiveData(flowControlledBytes: 1024, isEndStreamSet: false)\n successful = successful && client.sendWindowUpdate(windowIncrement: 1024)\n successful = successful && server.receiveWindowUpdate(windowIncrement: 1024)\n\n successful = successful && server.sendData(flowControlledBytes: 1024, isEndStreamSet: true)\n successful = successful && client.receiveData(flowControlledBytes: 1024, isEndStreamSet: true)\n\n return successful\n}\n\n@inline(never)\nfunc testPushedRequests(_ n: Int) -> Bool {\n var successful = true\n\n var server = HTTP2StreamStateMachine(sentPushPromiseWithLocalInitialWindowSize: n)\n var client = HTTP2StreamStateMachine(receivedPushPromiseWithRemoteInitialWindowSize: n)\n\n successful = successful && client.sendWindowUpdate(windowIncrement: 1024)\n\n successful = successful && server.sendHeaders(isEndStreamSet: false)\n successful = successful && client.receiveHeaders(isEndStreamSet: false)\n\n successful = successful && server.sendData(flowControlledBytes: 1024, isEndStreamSet: false)\n successful = successful && server.sendData(flowControlledBytes: 1024, isEndStreamSet: false)\n successful = successful && client.receiveData(flowControlledBytes: 1024, isEndStreamSet: false)\n successful = successful && client.receiveData(flowControlledBytes: 1024, isEndStreamSet: false)\n\n successful = successful && client.sendWindowUpdate(windowIncrement: 1024)\n successful = successful && server.receiveWindowUpdate(windowIncrement: 1024)\n\n successful = successful && server.sendData(flowControlledBytes: 1024, isEndStreamSet: false)\n successful = successful && client.receiveData(flowControlledBytes: 1024, isEndStreamSet: false)\n\n successful = successful && server.sendHeaders(isEndStreamSet: true)\n successful = successful && client.receiveHeaders(isEndStreamSet: true)\n\n return successful\n}\n\n@inline(never)\nfunc testPushingRequests(_ n: Int) -> Bool {\n var successful = true\n\n var server = HTTP2StreamStateMachine(localRole: .server, localWindow: 1<<16, remoteWindow: n)\n var client = HTTP2StreamStateMachine(localRole: .client, localWindow: 1<<16, remoteWindow: n)\n\n successful = successful && client.sendHeaders(isEndStreamSet: true)\n successful = successful && server.receiveHeaders(isEndStreamSet: true)\n\n successful = successful && server.sendHeaders(isEndStreamSet: false)\n successful = successful && client.receiveHeaders(isEndStreamSet: false)\n\n successful = successful && server.sendPushPromise()\n successful = successful && client.receivePushPromise()\n\n successful = successful && server.sendData(flowControlledBytes: 1024, isEndStreamSet: true)\n successful = successful && client.receiveData(flowControlledBytes: 1024, isEndStreamSet: true)\n\n return successful\n}\n\n@inline(never)\nfunc run_HTTP2StateMachine(_ n: Int) {\n for i in 0 ..< 100000 * n {\n check(testSimpleRequestResponse(identity(i)))\n check(testPushedRequests(identity(i)))\n check(testPushingRequests(identity(i)))\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_HTTP2StateMachine.swift | cpp_apple_swift_benchmark_single-source_HTTP2StateMachine.swift | Swift | 19,017 | 0.95 | 0.028205 | 0.052805 | awesome-app | 459 | 2025-02-28T02:53:24.077023 | BSD-3-Clause | false | 2fbfbc9aad3c7e43c711cd9047706579 |
//===--- InsertCharacter.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\nlet t: [BenchmarkCategory] = [.validation, .api, .String]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "InsertCharacterEndIndex",\n runFunction: run_InsertCharacterEndIndex, tags: t,\n setUpFunction: buildWorkload),\n BenchmarkInfo(name: "InsertCharacterTowardsEndIndex",\n runFunction: run_InsertCharacterTowardsEndIndex, tags: t,\n setUpFunction: buildWorkload),\n BenchmarkInfo(name: "InsertCharacterStartIndex",\n runFunction: run_InsertCharacterStartIndex, tags: t,\n setUpFunction: buildWorkload, legacyFactor: 5),\n BenchmarkInfo(name: "InsertCharacterEndIndexNonASCII",\n runFunction: run_InsertCharacterEndIndexNonASCII, tags: t,\n setUpFunction: buildWorkload),\n BenchmarkInfo(name: "InsertCharacterTowardsEndIndexNonASCII",\n runFunction: run_InsertCharacterTowardsEndIndexNonASCII, tags: t,\n setUpFunction: buildWorkload),\n BenchmarkInfo(name: "InsertCharacterStartIndexNonASCII",\n runFunction: run_InsertCharacterStartIndexNonASCII, tags: t,\n setUpFunction: buildWorkload)\n]\n\nlet str = String(repeating: "A very long ASCII string.", count: 200)\n\nfunc buildWorkload() {\n blackHole(str)\n}\n\n// Insert towards end index\n\n@inline(__always)\nfunc insertTowardsEndIndex(_ c: Character, in string: String, count: Int) {\n var workload = string\n var index = workload.endIndex\n for i in 0..<count {\n workload.insert(identity(c), at: index)\n if i % 1000 == 0 {\n index = workload.endIndex\n }\n }\n blackHole(workload)\n}\n\n@inline(never)\nfunc run_InsertCharacterTowardsEndIndex(_ n: Int) {\n insertTowardsEndIndex("s", in: str, count: n * 3000)\n}\n\n@inline(never)\nfunc run_InsertCharacterTowardsEndIndexNonASCII(_ n: Int) {\n insertTowardsEndIndex("👩🏼💻", in: str, count: n * 1000)\n}\n\n// Insert at end index\n\n@inline(__always)\nfunc insertAtEndIndex(_ c: Character, in string: String, count: Int) {\n var workload = string\n for _ in 0..<count {\n workload.insert(identity(c), at: workload.endIndex)\n }\n blackHole(workload)\n}\n\n@inline(never)\nfunc run_InsertCharacterEndIndex(_ n: Int) {\n insertAtEndIndex("s", in: str, count: n * 3000)\n}\n\n@inline(never)\nfunc run_InsertCharacterEndIndexNonASCII(_ n: Int) {\n insertAtEndIndex("👩🏾🏫", in: str, count: n * 1000)\n}\n\n// Insert at start index\n\n@inline(__always)\nfunc insertAtStartIndex(\n _ c: Character, in string: String, count: Int, insertions: Int) {\n var workload = str\n for _ in 0..<count {\n for _ in 0..<insertions {\n workload.insert(identity(c), at: workload.startIndex)\n }\n workload = str\n }\n blackHole(workload)\n}\n\n@inline(never)\nfunc run_InsertCharacterStartIndex(_ n: Int) {\n insertAtStartIndex("w", in: str, count: n * 15, insertions: 50)\n}\n\n@inline(never)\nfunc run_InsertCharacterStartIndexNonASCII(_ n: Int) {\n insertAtStartIndex("👩🏾🏫", in: str, count: n * 75, insertions: 25)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_InsertCharacter.swift | cpp_apple_swift_benchmark_single-source_InsertCharacter.swift | Swift | 3,383 | 0.95 | 0.061947 | 0.145833 | react-lib | 125 | 2024-07-29T03:43:11.433257 | Apache-2.0 | false | 6d94fb15b6a8c7195f71d7b3f0dea3dc |
//===--- IntegerParsing.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n\n// - Definitions\npublic let benchmarks = [\n // IntSmall\n BenchmarkInfo(name: "ParseInt.IntSmall.Decimal",\n runFunction: run_ParseIntFromIntSmallDecimal,\n tags: [.validation, .api],\n setUpFunction: {\n blackHole(intSmallValuesSum)\n blackHole(intSmallDecimalStrings)\n }),\n BenchmarkInfo(name: "ParseInt.IntSmall.Binary",\n runFunction: run_ParseIntFromIntSmallBinary,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(intSmallValuesSum)\n blackHole(intSmallBinaryStrings)\n }),\n BenchmarkInfo(name: "ParseInt.IntSmall.Hex",\n runFunction: run_ParseIntFromIntSmallHex,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(intSmallValuesSum)\n blackHole(intSmallHexStrings)\n }),\n BenchmarkInfo(name: "ParseInt.IntSmall.UncommonRadix",\n runFunction: run_ParseIntFromIntSmallUncommonRadix,\n tags: [.validation, .api],\n setUpFunction: {\n blackHole(intSmallValuesSum)\n blackHole(intSmallUncommonRadixStrings)\n }),\n // UIntSmall\n BenchmarkInfo(name: "ParseInt.UIntSmall.Decimal",\n runFunction: run_ParseIntFromUIntSmallDecimal,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uintSmallValuesSum)\n blackHole(uintSmallDecimalStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UIntSmall.Binary",\n runFunction: run_ParseIntFromUIntSmallBinary,\n tags: [.validation, .api],\n setUpFunction: {\n blackHole(uintSmallValuesSum)\n blackHole(uintSmallBinaryStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UIntSmall.Hex",\n runFunction: run_ParseIntFromUIntSmallHex,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uintSmallValuesSum)\n blackHole(uintSmallHexStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UIntSmall.UncommonRadix",\n runFunction: run_ParseIntFromUIntSmallUncommonRadix,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uintSmallValuesSum)\n blackHole(uintSmallUncommonRadixStrings)\n }),\n // Int32\n BenchmarkInfo(name: "ParseInt.Int32.Decimal",\n runFunction: run_ParseIntFromInt32Decimal,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(int32ValuesSum)\n blackHole(int32DecimalStrings)\n }),\n BenchmarkInfo(name: "ParseInt.Int32.Binary",\n runFunction: run_ParseIntFromInt32Binary,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(int32ValuesSum)\n blackHole(int32BinaryStrings)\n }),\n BenchmarkInfo(name: "ParseInt.Int32.Hex",\n runFunction: run_ParseIntFromInt32Hex,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(int32ValuesSum)\n blackHole(int32HexStrings)\n }),\n BenchmarkInfo(name: "ParseInt.Int32.UncommonRadix",\n runFunction: run_ParseIntFromInt32UncommonRadix,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(int32ValuesSum)\n blackHole(int32UncommonRadixStrings)\n }),\n // Int64\n BenchmarkInfo(name: "ParseInt.Int64.Decimal",\n runFunction: run_ParseIntFromInt64Decimal,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(int64ValuesSum)\n blackHole(int64DecimalStrings)\n }),\n BenchmarkInfo(name: "ParseInt.Int64.Binary",\n runFunction: run_ParseIntFromInt64Binary,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(int64ValuesSum)\n blackHole(int64BinaryStrings)\n }),\n BenchmarkInfo(name: "ParseInt.Int64.Hex",\n runFunction: run_ParseIntFromInt64Hex,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(int64ValuesSum)\n blackHole(int64HexStrings)\n }),\n BenchmarkInfo(name: "ParseInt.Int64.UncommonRadix",\n runFunction: run_ParseIntFromInt64UncommonRadix,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(int64ValuesSum)\n blackHole(int64UncommonRadixStrings)\n }),\n // UInt32\n BenchmarkInfo(name: "ParseInt.UInt32.Decimal",\n runFunction: run_ParseIntFromUInt32Decimal,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uint32ValuesSum)\n blackHole(uint32DecimalStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UInt32.Binary",\n runFunction: run_ParseIntFromUInt32Binary,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uint32ValuesSum)\n blackHole(uint32BinaryStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UInt32.Hex",\n runFunction: run_ParseIntFromUInt32Hex,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uint32ValuesSum)\n blackHole(uint32HexStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UInt32.UncommonRadix",\n runFunction: run_ParseIntFromUInt32UncommonRadix,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uint32ValuesSum)\n blackHole(uint32UncommonRadixStrings)\n }),\n // UInt64\n BenchmarkInfo(name: "ParseInt.UInt64.Decimal",\n runFunction: run_ParseIntFromUInt64Decimal,\n tags: [.validation, .api],\n setUpFunction: {\n blackHole(uint64ValuesSum)\n blackHole(uint64DecimalStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UInt64.Binary",\n runFunction: run_ParseIntFromUInt64Binary,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uint64ValuesSum)\n blackHole(uint64BinaryStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UInt64.Hex",\n runFunction: run_ParseIntFromUInt64Hex,\n tags: [.validation, .api],\n setUpFunction: {\n blackHole(uint64ValuesSum)\n blackHole(uint64HexStrings)\n }),\n BenchmarkInfo(name: "ParseInt.UInt64.UncommonRadix",\n runFunction: run_ParseIntFromUInt64UncommonRadix,\n tags: [.validation, .api, .skip],\n setUpFunction: {\n blackHole(uint64ValuesSum)\n blackHole(uint64UncommonRadixStrings)\n }),\n]\n\n// - Verification Sums\nprivate let intSmallValuesSum: Int\n = intSmallValues.reduce(0, &+)\nprivate let uintSmallValuesSum: UInt\n = uintSmallValues.reduce(0, &+)\nprivate let int32ValuesSum: Int32\n = int32Values.reduce(0, &+)\nprivate let int64ValuesSum: Int64\n = int64Values.reduce(0, &+)\nprivate let uint32ValuesSum: UInt32\n = uint32Values.reduce(0, &+)\nprivate let uint64ValuesSum: UInt64\n = uint64Values.reduce(0, &+)\n\n// - Values\nfunc generateValues<Integer : FixedWidthInteger>(\n in range: ClosedRange<Integer>, count: Int\n) -> [Integer] {\n var rng = SplitMix64(seed: 42)\n return (0..<count).map { _ in\n Integer.random(in: range, using: &rng)\n }\n}\nprivate let intSmallValues: [Int]\n = generateValues(in: -9999 ... 9999, count: 1000)\nprivate let uintSmallValues: [UInt]\n = generateValues(in: 0 ... 9999, count: 1000)\nprivate let int32Values: [Int32]\n = generateValues(in: .min ... .max, count: 1000)\nprivate let int64Values: [Int64]\n = generateValues(in: .min ... .max, count: 1000)\nprivate let uint32Values: [UInt32]\n = generateValues(in: .min ... .max, count: 1000)\nprivate let uint64Values: [UInt64]\n = generateValues(in: .min ... .max, count: 1000)\n\n// - Strings\n// IntSmall\nprivate let intSmallDecimalStrings: [String]\n = intSmallValues.map { String($0, radix: 10) }\nprivate let intSmallBinaryStrings: [String]\n = intSmallValues.map { String($0, radix: 2) }\nprivate let intSmallHexStrings: [String]\n = intSmallValues.map { String($0, radix: 16) }\nprivate let intSmallUncommonRadixStrings: [String]\n = intSmallValues.map { String($0, radix: 7) }\n// UIntSmall\nprivate let uintSmallDecimalStrings: [String]\n = uintSmallValues.map { String($0, radix: 10) }\nprivate let uintSmallBinaryStrings: [String]\n = uintSmallValues.map { String($0, radix: 2) }\nprivate let uintSmallHexStrings: [String]\n = uintSmallValues.map { String($0, radix: 16) }\nprivate let uintSmallUncommonRadixStrings: [String]\n = uintSmallValues.map { String($0, radix: 7) }\n// Int32\nprivate let int32DecimalStrings: [String]\n = int32Values.map { String($0, radix: 10) }\nprivate let int32BinaryStrings: [String]\n = int32Values.map { String($0, radix: 2) }\nprivate let int32HexStrings: [String]\n = int32Values.map { String($0, radix: 16) }\nprivate let int32UncommonRadixStrings: [String]\n = int32Values.map { String($0, radix: 7) }\n// Int64\nprivate let int64DecimalStrings: [String]\n = int64Values.map { String($0, radix: 10) }\nprivate let int64BinaryStrings: [String]\n = int64Values.map { String($0, radix: 2) }\nprivate let int64HexStrings: [String]\n = int64Values.map { String($0, radix: 16) }\nprivate let int64UncommonRadixStrings: [String]\n = int64Values.map { String($0, radix: 7) }\n// UInt32\nprivate let uint32DecimalStrings: [String]\n = uint32Values.map { String($0, radix: 10) }\nprivate let uint32BinaryStrings: [String]\n = uint32Values.map { String($0, radix: 2) }\nprivate let uint32HexStrings: [String]\n = uint32Values.map { String($0, radix: 16) }\nprivate let uint32UncommonRadixStrings: [String]\n = uint32Values.map { String($0, radix: 7) }\n// UInt64\nprivate let uint64DecimalStrings: [String]\n = uint64Values.map { String($0, radix: 10) }\nprivate let uint64BinaryStrings: [String]\n = uint64Values.map { String($0, radix: 2) }\nprivate let uint64HexStrings: [String]\n = uint64Values.map { String($0, radix: 16) }\nprivate let uint64UncommonRadixStrings: [String]\n = uint64Values.map { String($0, radix: 7) }\n\n// - Implementations\n\n// IntSmall\n@inline(never)\npublic func run_ParseIntFromIntSmallDecimal(n: Int) {\n var result: Int = 0\n let count = n * 20\n for _ in 0..<count {\n for string in intSmallDecimalStrings {\n result &+= Int(string, radix: 10)!\n }\n }\n check(result == intSmallValuesSum &* Int(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromIntSmallBinary(n: Int) {\n var result: Int = 0\n let count = n * 20\n for _ in 0..<count {\n for string in intSmallBinaryStrings {\n result &+= Int(string, radix: 2)!\n }\n }\n check(result == intSmallValuesSum &* Int(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromIntSmallHex(n: Int) {\n var result: Int = 0\n let count = n * 20\n for _ in 0..<count {\n for string in intSmallHexStrings {\n result &+= Int(string, radix: 16)!\n }\n }\n check(result == intSmallValuesSum &* Int(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromIntSmallUncommonRadix(n: Int) {\n var result: Int = 0\n let count = n * 20\n for _ in 0..<count {\n for string in intSmallUncommonRadixStrings {\n result &+= Int(string, radix: 7)!\n }\n }\n check(result == intSmallValuesSum &* Int(count))\n}\n\n// UIntSmall\n@inline(never)\npublic func run_ParseIntFromUIntSmallDecimal(n: Int) {\n var result: UInt = 0\n let count = n * 20\n for _ in 0..<count {\n for string in uintSmallDecimalStrings {\n result &+= UInt(string, radix: 10)!\n }\n }\n check(result == uintSmallValuesSum &* UInt(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUIntSmallBinary(n: Int) {\n var result: UInt = 0\n let count = n * 20\n for _ in 0..<count {\n for string in uintSmallBinaryStrings {\n result &+= UInt(string, radix: 2)!\n }\n }\n check(result == uintSmallValuesSum &* UInt(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUIntSmallHex(n: Int) {\n var result: UInt = 0\n let count = n * 20\n for _ in 0..<count {\n for string in uintSmallHexStrings {\n result &+= UInt(string, radix: 16)!\n }\n }\n check(result == uintSmallValuesSum &* UInt(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUIntSmallUncommonRadix(n: Int) {\n var result: UInt = 0\n let count = n * 20\n for _ in 0..<count {\n for string in uintSmallUncommonRadixStrings {\n result &+= UInt(string, radix: 7)!\n }\n }\n check(result == uintSmallValuesSum &* UInt(count))\n}\n\n// Int32\n@inline(never)\npublic func run_ParseIntFromInt32Decimal(n: Int) {\n var result: Int32 = 0\n let count = n * 8\n for _ in 0..<count {\n for string in int32DecimalStrings {\n result &+= Int32(string, radix: 10)!\n }\n }\n check(result == int32ValuesSum &* Int32(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromInt32Binary(n: Int) {\n var result: Int32 = 0\n let count = n * 8\n for _ in 0..<count {\n for string in int32BinaryStrings {\n result &+= Int32(string, radix: 2)!\n }\n }\n check(result == int32ValuesSum &* Int32(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromInt32Hex(n: Int) {\n var result: Int32 = 0\n let count = n * 8\n for _ in 0..<count {\n for string in int32HexStrings {\n result &+= Int32(string, radix: 16)!\n }\n }\n check(result == int32ValuesSum &* Int32(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromInt32UncommonRadix(n: Int) {\n var result: Int32 = 0\n let count = n * 8\n for _ in 0..<count {\n for string in int32UncommonRadixStrings {\n result &+= Int32(string, radix: 7)!\n }\n }\n check(result == int32ValuesSum &* Int32(count))\n}\n\n// Int64\n@inline(never)\npublic func run_ParseIntFromInt64Decimal(n: Int) {\n var result: Int64 = 0\n let count = n * 4\n for _ in 0..<count {\n for string in int64DecimalStrings {\n result &+= Int64(string, radix: 10)!\n }\n }\n check(result == int64ValuesSum &* Int64(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromInt64Binary(n: Int) {\n var result: Int64 = 0\n let count = n * 4\n for _ in 0..<count {\n for string in int64BinaryStrings {\n result &+= Int64(string, radix: 2)!\n }\n }\n check(result == int64ValuesSum &* Int64(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromInt64Hex(n: Int) {\n var result: Int64 = 0\n let count = n * 4\n for _ in 0..<count {\n for string in int64HexStrings {\n result &+= Int64(string, radix: 16)!\n }\n }\n check(result == int64ValuesSum &* Int64(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromInt64UncommonRadix(n: Int) {\n var result: Int64 = 0\n let count = n * 4\n for _ in 0..<count {\n for string in int64UncommonRadixStrings {\n result &+= Int64(string, radix: 7)!\n }\n }\n check(result == int64ValuesSum &* Int64(count))\n}\n\n// UInt32\n@inline(never)\npublic func run_ParseIntFromUInt32Decimal(n: Int) {\n var result: UInt32 = 0\n let count = n * 8\n for _ in 0..<count {\n for string in uint32DecimalStrings {\n result &+= UInt32(string, radix: 10)!\n }\n }\n check(result == uint32ValuesSum &* UInt32(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUInt32Binary(n: Int) {\n var result: UInt32 = 0\n let count = n * 8\n for _ in 0..<count {\n for string in uint32BinaryStrings {\n result &+= UInt32(string, radix: 2)!\n }\n }\n check(result == uint32ValuesSum &* UInt32(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUInt32Hex(n: Int) {\n var result: UInt32 = 0\n let count = n * 8\n for _ in 0..<count {\n for string in uint32HexStrings {\n result &+= UInt32(string, radix: 16)!\n }\n }\n check(result == uint32ValuesSum &* UInt32(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUInt32UncommonRadix(n: Int) {\n var result: UInt32 = 0\n let count = n * 8\n for _ in 0..<count {\n for string in uint32UncommonRadixStrings {\n result &+= UInt32(string, radix: 7)!\n }\n }\n check(result == uint32ValuesSum &* UInt32(count))\n}\n\n// UInt64\n@inline(never)\npublic func run_ParseIntFromUInt64Decimal(n: Int) {\n var result: UInt64 = 0\n let count = n * 4\n for _ in 0..<count {\n for string in uint64DecimalStrings {\n result &+= UInt64(string, radix: 10)!\n }\n }\n check(result == uint64ValuesSum &* UInt64(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUInt64Binary(n: Int) {\n var result: UInt64 = 0\n let count = n * 4\n for _ in 0..<count {\n for string in uint64BinaryStrings {\n result &+= UInt64(string, radix: 2)!\n }\n }\n check(result == uint64ValuesSum &* UInt64(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUInt64Hex(n: Int) {\n var result: UInt64 = 0\n let count = n * 4\n for _ in 0..<count {\n for string in uint64HexStrings {\n result &+= UInt64(string, radix: 16)!\n }\n }\n check(result == uint64ValuesSum &* UInt64(count))\n}\n\n@inline(never)\npublic func run_ParseIntFromUInt64UncommonRadix(n: Int) {\n var result: UInt64 = 0\n let count = n * 4\n for _ in 0..<count {\n for string in uint64UncommonRadixStrings {\n result &+= UInt64(string, radix: 7)!\n }\n }\n check(result == uint64ValuesSum &* UInt64(count))\n}\n\n\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_IntegerParsing.swift | cpp_apple_swift_benchmark_single-source_IntegerParsing.swift | Swift | 16,606 | 0.95 | 0.085763 | 0.061931 | python-kit | 650 | 2025-01-21T23:57:50.719746 | MIT | false | 786fde90e338079f25ddb1093edcb2dd |
//===--- IterateData.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Foundation\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "IterateData",\n runFunction: run_IterateData,\n tags: [.validation, .api, .Data],\n setUpFunction: { blackHole(data) })\n\nlet data: Data = {\n var data = Data(count: 16 * 1024)\n let n = data.count\n data.withUnsafeMutableBytes { (ptr: UnsafeMutablePointer<UInt8>) -> () in\n for i in 0..<n {\n ptr[i] = UInt8(i % 23)\n }\n }\n return data\n}()\n\n@inline(never)\npublic func run_IterateData(_ n: Int) {\n for _ in 1...10*n {\n _ = data.reduce(0, &+)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_IterateData.swift | cpp_apple_swift_benchmark_single-source_IterateData.swift | Swift | 1,077 | 0.95 | 0.102564 | 0.314286 | node-utils | 893 | 2023-10-18T04:22:39.634947 | BSD-3-Clause | false | 2ae51ce26148bca18ac29cd576374ce6 |
//===--- Join.swift -------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test tests the performance of ASCII Character comparison.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Join",\n runFunction: run_Join,\n tags: [.validation, .api, .String, .Array])\n\n@inline(never)\npublic func run_Join(_ n: Int) {\n var array: [String] = []\n for x in 0..<1000 * n {\n array.append(String(x))\n }\n _ = array.joined(separator: "")\n _ = array.joined(separator: " ")\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Join.swift | cpp_apple_swift_benchmark_single-source_Join.swift | Swift | 944 | 0.95 | 0.1 | 0.444444 | awesome-app | 771 | 2024-12-15T19:19:46.605022 | BSD-3-Clause | false | c4e6e865938c36edf54b063f87b28696 |
//===--- LazyFilter.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance of creating an array from lazily filtered\n// collections.\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "LazilyFilteredArrays2",\n runFunction: run_LazilyFilteredArrays,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(filteredRange) },\n legacyFactor: 100),\n BenchmarkInfo(name: "LazilyFilteredRange",\n runFunction: run_LazilyFilteredRange,\n tags: [.validation, .api, .Array],\n legacyFactor: 10),\n BenchmarkInfo(\n name: "LazilyFilteredArrayContains",\n runFunction: run_LazilyFilteredArrayContains,\n tags: [.validation, .api, .Array],\n setUpFunction: {\n multiplesOfThree = Array(1..<500).lazy.filter { $0 % 3 == 0 } },\n tearDownFunction: { multiplesOfThree = nil },\n legacyFactor: 100),\n]\n\n@inline(never)\npublic func run_LazilyFilteredRange(_ n: Int) {\n var res = 123\n let c = (1..<100_000).lazy.filter { $0 % 7 == 0 }\n for _ in 1...n {\n res += Array(c).count\n res -= Array(c).count\n }\n check(res == 123)\n}\n\nlet filteredRange = (1..<1_000).map({[$0]}).lazy.filter { $0.first! % 7 == 0 }\n\n@inline(never)\npublic func run_LazilyFilteredArrays(_ n: Int) {\n var res = 123\n let c = filteredRange\n for _ in 1...n {\n res += Array(c).count\n res -= Array(c).count\n }\n check(res == 123)\n}\n\nfileprivate var multiplesOfThree: LazyFilterCollection<Array<Int>>?\n\n@inline(never)\nfileprivate func run_LazilyFilteredArrayContains(_ n: Int) {\n let xs = multiplesOfThree!\n for _ in 1...n {\n var filteredCount = 0\n for candidate in 1..<500 {\n filteredCount += xs.contains(candidate) ? 1 : 0\n }\n check(filteredCount == 166)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_LazyFilter.swift | cpp_apple_swift_benchmark_single-source_LazyFilter.swift | Swift | 2,181 | 0.95 | 0.082192 | 0.19697 | awesome-app | 52 | 2024-04-01T13:19:48.654016 | MIT | false | 02c1a785f5c82cbf70812fa7eaae599d |
//===--- LinkedList.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance of linked lists. It is based on LinkedList from\n// utils/benchmark, with modifications for performance measuring.\nimport TestsUtils\n\n// 47% _swift_retain\n// 43% _swift_release\npublic let benchmarks =\n BenchmarkInfo(\n name: "LinkedList",\n runFunction: run_LinkedList,\n tags: [.runtime, .cpubench, .refcount],\n setUpFunction: { for i in 0..<size { head = Node(n:head, d:i) } },\n tearDownFunction: { head = Node(n:nil, d:0) },\n legacyFactor: 40)\n\nlet size = 100\nvar head = Node(n:nil, d:0)\n\nfinal class Node {\n var next: Node?\n var data: Int\n\n init(n: Node?, d: Int) {\n next = n\n data = d\n }\n}\n\n@inline(never)\npublic func run_LinkedList(_ n: Int) {\n var sum = 0\n let ref_result = size*(size-1)/2\n var ptr = head\n for _ in 1...125*n {\n ptr = head\n sum = 0\n while let nxt = ptr.next {\n sum += ptr.data\n ptr = nxt\n }\n if sum != ref_result {\n break\n }\n }\n check(sum == ref_result)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_LinkedList.swift | cpp_apple_swift_benchmark_single-source_LinkedList.swift | Swift | 1,496 | 0.95 | 0.137931 | 0.288462 | python-kit | 915 | 2023-11-08T03:17:04.890497 | MIT | false | 836d7fa425fe50b786d4ae5aafafc7c2 |
// LuhnAlgoEager benchmark\n//\n// Description: Performs a Luhn checksum eagerly\n// Source: https://gist.github.com/airspeedswift/e584239d7658b317f59a\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "LuhnAlgoEager",\n runFunction: run_LuhnAlgoEager,\n tags: [.algorithm]\n ),\n]\n\n@inline(never)\npublic func run_LuhnAlgoEager(_ n: Int) {\n let resultRef = true\n var result = false\n\n for _ in 1...100*n {\n result = eagerchecksum(ccnum)\n\n if result != resultRef {\n break\n }\n }\n\n check(result == resultRef)\n}\n\n// Another version of the Luhn algorithm, similar to the one found here:\n// https://gist.github.com/airspeedswift/b349c256e90da746b852\n//\n// This time, trying to keep two versions, one eager one lazy,\n// as similar as possible. Only adding "lazy" to the start of\n// the expression to switch between the two.\n//\n// Much of the same code as the previous version at the top,\n// Skip down to line 110 for the different par\n\n// mapSome is my Swift version of Haskell's mapMaybe, which\n// is a map that takes a transform function that returns an\n// optional, and returns a collection of only those values\n// that weren't nil\n\n// first we need a lazy view that holds the original\n// sequence and the transform function\nstruct MapSomeSequenceView<Base: Sequence, T> {\n fileprivate let _base: Base\n fileprivate let _transform: (Base.Element) -> T?\n}\n\n// extend it to implement Sequence\nextension MapSomeSequenceView: Sequence {\n typealias Iterator = AnyIterator<T>\n\n func makeIterator() -> Iterator {\n var g = _base.makeIterator()\n // AnyIterator is a helper that takes a\n // closure and calls it to generate each\n // element\n return AnyIterator {\n while let element = g.next() {\n if let some = self._transform(element) {\n return some\n }\n }\n return nil\n }\n }\n}\n\n// now extend a lazy collection to return that view\n// from a call to mapSome. In practice, when doing this,\n// you should do it for all the lazy wrappers\n// (i.e. random-access, forward and sequence)\nextension LazyCollectionProtocol {\n // I might be missing a trick with this super-ugly return type, is there a\n // better way?\n func mapSome<U>(\n _ transform: @escaping (Elements.Element) -> U?\n ) -> LazySequence<MapSomeSequenceView<Elements, U>> {\n return MapSomeSequenceView(_base: elements, _transform: transform).lazy\n }\n}\n\n// curried function - call with 1 argument to get a function\n// that tells you if i is a multiple of a given number\n// e.g.\n// let isEven = isMultipleOf(2)\n// isEven(4) // true\nfunc isMultipleOf<T: FixedWidthInteger>(_ of: T)->(T)->Bool {\n return { $0 % of == 0 }\n}\n\n// extend LazySequence to map only every nth element, with all\n// other elements untransformed.\nextension LazySequenceProtocol {\n func mapEveryN(\n _ n: Int,\n _ transform: @escaping (Element) -> Element\n ) -> LazyMapSequence<EnumeratedSequence<Self>, Element> {\n let isNth = isMultipleOf(n)\n func transform2(\n _ pair: EnumeratedSequence<Self>.Element\n ) -> Element {\n return isNth(pair.0 + 1) ? transform(pair.1) : pair.1\n }\n return self.enumerated().lazy.map(transform2)\n }\n}\n\ninfix operator |> : PipeRightPrecedence\nprecedencegroup PipeRightPrecedence {\n associativity: left\n}\n\nfunc |><T,U>(t: T, f: (T)->U) -> U {\n return f(t)\n}\n\ninfix operator • : DotPrecedence\nprecedencegroup DotPrecedence {\n associativity: left\n}\n\nfunc • <T, U, V> (g: @escaping (U) -> V, f: @escaping (T) -> U) -> (T) -> V {\n return { x in g(f(x)) }\n}\n\n// function to free a method from the shackles\n// of it's owner\nfunc freeMemberFunc<T,U>(_ f: @escaping (T)->()->U)->(T)->U {\n return { (t: T)->U in f(t)() }\n}\n\nextension String {\n func toInt() -> Int? { return Int(self) }\n}\n\n// stringToInt can now be pipelined or composed\nlet stringToInt = freeMemberFunc(String.toInt)\n// if only Character also had a toInt method\nlet charToString = { (c: Character) -> String in String(c) }\nlet charToInt = stringToInt • charToString\n\nfunc sum<S: Sequence>(_ nums: S)->S.Element where S.Element: FixedWidthInteger {\n return nums.reduce(0, +)\n}\n\nfunc reverse<C: LazyCollectionProtocol>(\n _ source: C\n) -> LazyCollection<ReversedCollection<C.Elements>> {\n return source.elements.reversed().lazy\n}\n\nfunc map<S: LazySequenceProtocol, U>(\n _ source: S, _ transform: @escaping (S.Elements.Element)->U\n) -> LazyMapSequence<S.Elements,U> {\n return source.map(transform)\n}\n\nfunc mapSome<C: LazyCollectionProtocol, U>(\n _ source: C,\n _ transform: @escaping (C.Elements.Element)->U?\n) -> LazySequence<MapSomeSequenceView<C.Elements, U>> {\n return source.mapSome(transform)\n}\n\nfunc mapEveryN<S: LazySequenceProtocol>(\n _ source: S, _ n: Int,\n _ transform: @escaping (S.Element)->S.Element\n) -> LazyMapSequence<EnumeratedSequence<S>, S.Element> {\n return source.mapEveryN(n, transform)\n}\n\n// Non-lazy version of mapSome:\nfunc mapSome<S: Sequence, C: RangeReplaceableCollection>(\n _ source: S,\n _ transform: @escaping (S.Element)->C.Element?\n) -> C {\n var result = C()\n for x in source {\n if let y = transform(x) {\n result.append(y)\n }\n }\n return result\n}\n\n// Specialized default version of mapSome that returns an array, to avoid\n// forcing the user having to specify:\nfunc mapSome<S: Sequence,U>(\n _ source: S,\n _ transform: @escaping (S.Element\n)->U?)->[U] {\n // just calls the more generalized version\n return mapSome(source, transform)\n}\n\n// Non-lazy version of mapEveryN:\nfunc mapEveryN<S: Sequence>(\n _ source: S, _ n: Int,\n _ transform: @escaping (S.Element) -> S.Element\n) -> [S.Element] {\n let isNth = isMultipleOf(n)\n return source.enumerated().map {\n (pair: (offset: Int, element: S.Element)) in\n isNth(pair.offset+1)\n ? transform(pair.element)\n : pair.element\n }\n}\n\nlet double = { $0*2 }\n\nlet combineDoubleDigits = {\n (10...18).contains($0) ? $0-9 : $0\n}\n\n// removing lazy at start of pipeline\n// switches to array-based version\nlet eagerchecksum = { (ccnum: String) -> Bool in\n ccnum //.lazy\n |> { $0.reversed().lazy }\n |> { mapSome($0, charToInt) }\n |> { mapEveryN($0, 2, double) }\n |> { map($0, combineDoubleDigits) }\n |> sum\n |> isMultipleOf(10)\n}\n\nlet ccnum = "4012 8888 8888 1881"\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_LuhnAlgoEager.swift | cpp_apple_swift_benchmark_single-source_LuhnAlgoEager.swift | Swift | 6,465 | 0.95 | 0.068376 | 0.233831 | react-lib | 798 | 2024-11-14T13:08:05.504382 | MIT | false | ac3a940e8b36588efe12ef758b0af3c2 |
// LuhnAlgoLazy benchmark\n//\n// Description: Performs a Luhn checksum lazily\n// Source: https://gist.github.com/airspeedswift/e584239d7658b317f59a\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "LuhnAlgoLazy",\n runFunction: run_LuhnAlgoLazy,\n tags: [.algorithm]\n ),\n]\n\n@inline(never)\npublic func run_LuhnAlgoLazy(_ n: Int) {\n let resultRef = true\n var result = false\n\n for _ in 1...100*n {\n result = lazychecksum(ccnum)\n\n if result != resultRef {\n break\n }\n }\n\n check(result == resultRef)\n}\n\n// Another version of the Luhn algorithm, similar to the one found here:\n// https://gist.github.com/airspeedswift/b349c256e90da746b852\n//\n// This time, trying to keep two versions, one eager one lazy,\n// as similar as possible. Only adding "lazy" to the start of\n// the expression to switch between the two.\n//\n// Much of the same code as the previous version at the top,\n// Skip down to line 110 for the different par\n\n// mapSome is my Swift version of Haskell's mapMaybe, which\n// is a map that takes a transform function that returns an\n// optional, and returns a collection of only those values\n// that weren't nil\n\n// first we need a lazy view that holds the original\n// sequence and the transform function\nstruct MapSomeSequenceView<Base: Sequence, T> {\n fileprivate let _base: Base\n fileprivate let _transform: (Base.Element) -> T?\n}\n\n// extend it to implement Sequence\nextension MapSomeSequenceView: Sequence {\n typealias Iterator = AnyIterator<T>\n\n func makeIterator() -> Iterator {\n var g = _base.makeIterator()\n // AnyIterator is a helper that takes a\n // closure and calls it to generate each\n // element\n return AnyIterator {\n while let element = g.next() {\n if let some = self._transform(element) {\n return some\n }\n }\n return nil\n }\n }\n}\n\n// now extend a lazy collection to return that view\n// from a call to mapSome. In practice, when doing this,\n// you should do it for all the lazy wrappers\n// (i.e. random-access, forward and sequence)\nextension LazyCollectionProtocol {\n // I might be missing a trick with this super-ugly return type, is there a\n // better way?\n func mapSome<U>(\n _ transform: @escaping (Elements.Element) -> U?\n ) -> LazySequence<MapSomeSequenceView<Elements, U>> {\n return MapSomeSequenceView(_base: elements, _transform: transform).lazy\n }\n}\n\n// curried function - call with 1 argument to get a function\n// that tells you if i is a multiple of a given number\n// e.g.\n// let isEven = isMultipleOf(2)\n// isEven(4) // true\nfunc isMultipleOf<T: FixedWidthInteger>(_ of: T)->(T)->Bool {\n return { $0 % of == 0 }\n}\n\n// extend LazySequence to map only every nth element, with all\n// other elements untransformed.\nextension LazySequenceProtocol {\n func mapEveryN(\n _ n: Int,\n _ transform: @escaping (Element) -> Element\n ) -> LazyMapSequence<EnumeratedSequence<Self>, Element> {\n let isNth = isMultipleOf(n)\n func transform2(\n _ pair: EnumeratedSequence<Self>.Element\n ) -> Element {\n return isNth(pair.0 + 1) ? transform(pair.1) : pair.1\n }\n return self.enumerated().lazy.map(transform2)\n }\n}\n\ninfix operator |> : PipeRightPrecedence\nprecedencegroup PipeRightPrecedence {\n associativity: left\n}\n\nfunc |><T,U>(t: T, f: (T)->U) -> U {\n return f(t)\n}\n\ninfix operator • : DotPrecedence\nprecedencegroup DotPrecedence {\n associativity: left\n}\n\nfunc • <T, U, V> (g: @escaping (U) -> V, f: @escaping (T) -> U) -> (T) -> V {\n return { x in g(f(x)) }\n}\n\n// function to free a method from the shackles\n// of it's owner\nfunc freeMemberFunc<T,U>(_ f: @escaping (T)->()->U)->(T)->U {\n return { (t: T)->U in f(t)() }\n}\n\nextension String {\n func toInt() -> Int? { return Int(self) }\n}\n\n// stringToInt can now be pipelined or composed\nlet stringToInt = freeMemberFunc(String.toInt)\n// if only Character also had a toInt method\nlet charToString = { (c: Character) -> String in String(c) }\nlet charToInt = stringToInt • charToString\n\nfunc sum<S: Sequence>(_ nums: S)->S.Element where S.Element: FixedWidthInteger {\n return nums.reduce(0,+)\n}\n\nfunc reverse<C: LazyCollectionProtocol>(\n _ source: C\n) -> LazyCollection<ReversedCollection<C.Elements>> {\n return source.elements.reversed().lazy\n}\n\nfunc map<S: LazySequenceProtocol, U>(\n _ source: S, _ transform: @escaping (S.Elements.Element)->U\n) -> LazyMapSequence<S.Elements,U> {\n return source.map(transform)\n}\n\nfunc mapSome<C: LazyCollectionProtocol, U>(\n _ source: C,\n _ transform: @escaping (C.Elements.Element)->U?\n) -> LazySequence<MapSomeSequenceView<C.Elements, U>> {\n return source.mapSome(transform)\n}\n\nfunc mapEveryN<S: LazySequenceProtocol>(\n _ source: S, _ n: Int,\n _ transform: @escaping (S.Element)->S.Element\n) -> LazyMapSequence<EnumeratedSequence<S>, S.Element> {\n return source.mapEveryN(n, transform)\n}\n\n// Non-lazy version of mapSome:\nfunc mapSome<S: Sequence, C: RangeReplaceableCollection>(\n _ source: S,\n _ transform: @escaping (S.Element)->C.Element?\n) -> C {\n var result = C()\n for x in source {\n if let y = transform(x) {\n result.append(y)\n }\n }\n return result\n}\n\n// Specialized default version of mapSome that returns an array, to avoid\n// forcing the user having to specify:\nfunc mapSome<S: Sequence,U>(\n _ source: S,\n _ transform: @escaping (S.Element\n)->U?)->[U] {\n // just calls the more generalized version\n return mapSome(source, transform)\n}\n\n// Non-lazy version of mapEveryN:\nfunc mapEveryN<S: Sequence>(\n _ source: S, _ n: Int,\n _ transform: @escaping (S.Element) -> S.Element\n) -> [S.Element] {\n let isNth = isMultipleOf(n)\n return source.enumerated().map {\n (pair: (offset: Int, element: S.Element)) in\n isNth(pair.offset+1)\n ? transform(pair.element)\n : pair.element\n }\n}\n\nlet double = { $0*2 }\n\nlet combineDoubleDigits = {\n (10...18).contains($0) ? $0-9 : $0\n}\n\n// first, the lazy version of checksum calculation\nlet lazychecksum = { (ccnum: String) -> Bool in\n ccnum.lazy\n |> reverse\n |> { mapSome($0, charToInt) }\n |> { mapEveryN($0, 2, double) }\n |> { map($0, combineDoubleDigits) }\n |> sum\n |> isMultipleOf(10)\n}\n\nlet ccnum = "4012 8888 8888 1881"\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_LuhnAlgoLazy.swift | cpp_apple_swift_benchmark_single-source_LuhnAlgoLazy.swift | Swift | 6,417 | 0.95 | 0.06867 | 0.23 | node-utils | 186 | 2024-12-02T00:28:13.594744 | MIT | false | 2ae53180a968955ac50a7e7b89be119b |
//===--- MapReduce.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Foundation\n\nlet t: [BenchmarkCategory] = [.validation, .algorithm]\nlet ts: [BenchmarkCategory] = [.validation, .algorithm, .String]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "MapReduce", runFunction: run_MapReduce, tags: t),\n BenchmarkInfo(name: "MapReduceAnyCollection",\n runFunction: run_MapReduceAnyCollection, tags: t),\n BenchmarkInfo(name: "MapReduceAnyCollectionShort",\n runFunction: run_MapReduceAnyCollectionShort, tags: t, legacyFactor: 10),\n BenchmarkInfo(name: "MapReduceClass2",\n runFunction: run_MapReduceClass, tags: t,\n setUpFunction: { boxedNumbers(1000) }, tearDownFunction: releaseDecimals),\n BenchmarkInfo(name: "MapReduceClassShort2",\n runFunction: run_MapReduceClassShort, tags: t,\n setUpFunction: { boxedNumbers(10) }, tearDownFunction: releaseDecimals),\n BenchmarkInfo(name: "MapReduceNSDecimalNumber",\n runFunction: run_MapReduceNSDecimalNumber, tags: t,\n setUpFunction: { decimals(1000) }, tearDownFunction: releaseDecimals),\n BenchmarkInfo(name: "MapReduceNSDecimalNumberShort",\n runFunction: run_MapReduceNSDecimalNumberShort, tags: t,\n setUpFunction: { decimals(10) }, tearDownFunction: releaseDecimals),\n BenchmarkInfo(name: "MapReduceLazyCollection",\n runFunction: run_MapReduceLazyCollection, tags: t),\n BenchmarkInfo(name: "MapReduceLazyCollectionShort",\n runFunction: run_MapReduceLazyCollectionShort, tags: t),\n BenchmarkInfo(name: "MapReduceLazySequence",\n runFunction: run_MapReduceLazySequence, tags: t),\n BenchmarkInfo(name: "MapReduceSequence",\n runFunction: run_MapReduceSequence, tags: t),\n BenchmarkInfo(name: "MapReduceShort",\n runFunction: run_MapReduceShort, tags: t, legacyFactor: 10),\n BenchmarkInfo(name: "MapReduceShortString",\n runFunction: run_MapReduceShortString, tags: ts),\n BenchmarkInfo(name: "MapReduceString",\n runFunction: run_MapReduceString, tags: ts),\n]\n\n#if _runtime(_ObjC)\nvar decimals : [NSDecimalNumber]!\nfunc decimals(_ n: Int) {\n decimals = (0..<n).map { NSDecimalNumber(value: $0) }\n}\nfunc releaseDecimals() { decimals = nil }\n#else\nfunc decimals(_ n: Int) {}\nfunc releaseDecimals() {}\n#endif\n\nclass Box {\n var v: Int\n init(_ v: Int) { self.v = v }\n}\n\nvar boxedNumbers : [Box]!\nfunc boxedNumbers(_ n: Int) { boxedNumbers = (0..<n).map { Box($0) } }\nfunc releaseboxedNumbers() { boxedNumbers = nil }\n\n@inline(never)\npublic func run_MapReduce(_ n: Int) {\n var numbers = [Int](0..<1000)\n\n var c = 0\n for _ in 1...n*100 {\n numbers = numbers.map { $0 &+ 5 }\n c = c &+ numbers.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceAnyCollection(_ n: Int) {\n let numbers = AnyCollection([Int](0..<1000))\n\n var c = 0\n for _ in 1...n*100 {\n let mapped = numbers.map { $0 &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceAnyCollectionShort(_ n: Int) {\n let numbers = AnyCollection([Int](0..<10))\n\n var c = 0\n for _ in 1...n*1_000 {\n let mapped = numbers.map { $0 &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceShort(_ n: Int) {\n var numbers = [Int](0..<10)\n\n var c = 0\n for _ in 1...n*1_000 {\n numbers = numbers.map { $0 &+ 5 }\n c = c &+ numbers.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceSequence(_ n: Int) {\n let numbers = sequence(first: 0) { $0 < 1000 ? $0 &+ 1 : nil }\n\n var c = 0\n for _ in 1...n*100 {\n let mapped = numbers.map { $0 &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceLazySequence(_ n: Int) {\n let numbers = sequence(first: 0) { $0 < 1000 ? $0 &+ 1 : nil }\n\n var c = 0\n for _ in 1...n*100 {\n let mapped = numbers.lazy.map { $0 &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceLazyCollection(_ n: Int) {\n let numbers = [Int](0..<1000)\n\n var c = 0\n for _ in 1...n*100 {\n let mapped = numbers.lazy.map { $0 &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceLazyCollectionShort(_ n: Int) {\n let numbers = [Int](0..<10)\n\n var c = 0\n for _ in 1...n*10000 {\n let mapped = numbers.lazy.map { $0 &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceString(_ n: Int) {\n let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789"\n\n var c: UInt64 = 0\n for _ in 1...n*100 {\n c = c &+ s.utf8.map { UInt64($0 &+ 5) }.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceShortString(_ n: Int) {\n let s = "12345"\n\n var c: UInt64 = 0\n for _ in 1...n*100 {\n c = c &+ s.utf8.map { UInt64($0 &+ 5) }.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceNSDecimalNumber(_ n: Int) {\n#if _runtime(_ObjC)\n let numbers: [NSDecimalNumber] = decimals\n\n var c = 0\n for _ in 1...n*10 {\n let mapped = numbers.map { $0.intValue &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n#endif\n}\n\n@inline(never)\npublic func run_MapReduceNSDecimalNumberShort(_ n: Int) {\n#if _runtime(_ObjC)\n let numbers: [NSDecimalNumber] = decimals\n\n var c = 0\n for _ in 1...n*1_000 {\n let mapped = numbers.map { $0.intValue &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n#endif\n}\n\n\n@inline(never)\npublic func run_MapReduceClass(_ n: Int) {\n let numbers: [Box] = boxedNumbers\n\n var c = 0\n for _ in 1...n*10 {\n let mapped = numbers.map { $0.v &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_MapReduceClassShort(_ n: Int) {\n let numbers: [Box] = boxedNumbers\n\n var c = 0\n for _ in 1...n*1_000 {\n let mapped = numbers.map { $0.v &+ 5 }\n c = c &+ mapped.reduce(0, &+)\n }\n check(c != 0)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_MapReduce.swift | cpp_apple_swift_benchmark_single-source_MapReduce.swift | Swift | 6,350 | 0.95 | 0.082645 | 0.086957 | vue-tools | 10 | 2025-05-26T09:48:08.632012 | BSD-3-Clause | false | 08a5f134b48fb44a279a96ab9a789c78 |
//===--- Memset.swift -----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Memset",\n runFunction: run_Memset,\n tags: [.validation, .unstable])\n\n@inline(never)\nfunc memset(_ a: inout [Int], _ c: Int) {\n for i in 0..<a.count {\n a[i] = c\n }\n}\n\n@inline(never)\npublic func run_Memset(_ n: Int) {\n var a = [Int](repeating: 0, count: 10_000)\n for _ in 1...50*n {\n memset(&a, 1)\n memset(&a, 0)\n }\n check(a[87] == 0)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Memset.swift | cpp_apple_swift_benchmark_single-source_Memset.swift | Swift | 947 | 0.95 | 0.111111 | 0.34375 | react-lib | 45 | 2025-02-20T16:52:37.533507 | MIT | false | a79f9dea0e7ee0d88650e75f7655f102 |
//===--- MonteCarloE.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test measures performance of Monte Carlo estimation of the e constant.\n//\n// We use 'dart' method: we split an interval into N pieces and drop N darts\n// to this interval.\n// After that we count number of empty intervals. The probability of being\n// empty is (1 - 1/N)^N which estimates to e^-1 for large N.\n// Thus, e = N / Nempty.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "MonteCarloE",\n runFunction: run_MonteCarloE,\n tags: [.validation, .algorithm],\n legacyFactor: 20)\n\npublic func run_MonteCarloE(scale: Int) {\n var lfsr = LFSR()\n\n let n = 10_000 * scale\n var intervals = [Bool](repeating: false, count: n)\n for _ in 1...n {\n let pos = Int(UInt(truncatingIfNeeded: lfsr.next()) % UInt(n))\n intervals[pos] = true\n }\n let numEmptyIntervals = intervals.filter{!$0}.count\n // If there are no empty intervals, then obviously the random generator is\n // not 'random' enough.\n check(numEmptyIntervals != n)\n let e_estimate = Double(n)/Double(numEmptyIntervals)\n let e = 2.71828\n check(abs(e_estimate - e) < 0.2)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_MonteCarloE.swift | cpp_apple_swift_benchmark_single-source_MonteCarloE.swift | Swift | 1,596 | 0.95 | 0.088889 | 0.487805 | python-kit | 91 | 2023-12-10T07:32:24.780293 | BSD-3-Clause | false | d5e95f96f72287932d61e907517ee66d |
//===--- MonteCarloPi.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "MonteCarloPi",\n runFunction: run_MonteCarloPi,\n tags: [.validation, .algorithm],\n legacyFactor: 125)\n\npublic func run_MonteCarloPi(scale: Int) {\n var rng = LFSR()\n\n var pointsInside = 0\n let r = 10000\n let n = 4_000*scale\n for _ in 1...n {\n let x = Int(truncatingIfNeeded: rng.next()) % r\n let y = Int(truncatingIfNeeded: rng.next()) % r\n if x*x + y*y < r*r {\n pointsInside += 1\n }\n }\n let pi_estimate: Double = Double(pointsInside)*4.0/Double(n)\n let pi = 3.1415\n check(abs(pi_estimate - pi) < 0.2)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_MonteCarloPi.swift | cpp_apple_swift_benchmark_single-source_MonteCarloPi.swift | Swift | 1,128 | 0.95 | 0.105263 | 0.323529 | react-lib | 916 | 2023-08-12T07:56:21.724284 | GPL-3.0 | false | 9279b96b3da49d598b93181c4598056a |
//===--- NaiveRangeReplaceableCollectionConformance.swift -----------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\nvar contiguous:[UInt8] = []\n\npublic let benchmarks = [\n BenchmarkInfo(name: "NaiveRRC.append.largeContiguous",\n runFunction: runAppendLargeContiguous,\n tags: [.validation, .api],\n setUpFunction: { contiguous = [UInt8](repeating: 7, count: 1_000) }),\n BenchmarkInfo(name: "NaiveRRC.append.smallContiguousRepeated",\n runFunction: runAppendSmallContiguousRepeatedly,\n tags: [.validation, .api],\n setUpFunction: { contiguous = [UInt8](repeating: 7, count: 1) }),\n BenchmarkInfo(name: "NaiveRRC.init.largeContiguous",\n runFunction: runInitLargeContiguous,\n tags: [.validation, .api],\n setUpFunction: { contiguous = [UInt8](repeating: 7, count: 1_000) })\n]\n\nstruct NaiveRRC : RangeReplaceableCollection {\n \n var storage:[UInt8] = []\n \n init() {}\n \n func index(after i: Int) -> Int {\n i + 1\n }\n \n func index(before i: Int) -> Int {\n i - 1\n }\n \n var startIndex: Int {\n 0\n }\n \n var endIndex: Int {\n count\n }\n \n var count: Int {\n storage.count\n }\n \n subscript(position: Int) -> UInt8 {\n get {\n storage[position]\n }\n set(newValue) {\n storage[position] = newValue\n }\n }\n \n mutating func replaceSubrange(_ subrange: Range<Int>, with newElements: some Collection<UInt8>) {\n storage.replaceSubrange(subrange, with: newElements)\n }\n \n mutating func reserveCapacity(_ n: Int) {\n storage.reserveCapacity(n)\n }\n}\n\n@inline(never)\npublic func runAppendLargeContiguous(N: Int) {\n for _ in 1...N {\n var rrc = NaiveRRC()\n rrc.append(contentsOf: contiguous)\n blackHole(rrc)\n }\n}\n\n@inline(never)\npublic func runAppendSmallContiguousRepeatedly(N: Int) {\n for _ in 1...N {\n var rrc = NaiveRRC()\n for _ in 1...5_000 {\n rrc.append(contentsOf: contiguous)\n }\n blackHole(rrc)\n }\n}\n\n@inline(never)\npublic func runInitLargeContiguous(N: Int) {\n for _ in 1...N {\n blackHole(NaiveRRC(contiguous))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_NaiveRangeReplaceableCollectionConformance.swift | cpp_apple_swift_benchmark_single-source_NaiveRangeReplaceableCollectionConformance.swift | Swift | 2,566 | 0.95 | 0.059406 | 0.130952 | node-utils | 490 | 2025-04-15T10:32:40.105727 | MIT | false | 99ca9667d5ea13698ddb4eb2f9e043e2 |
// NibbleSort benchmark\n//\n// Source: https://gist.github.com/airspeedswift/f4daff4ea5c6de9e1fdf\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "NibbleSort",\n runFunction: run_NibbleSort,\n tags: [.validation],\n legacyFactor: 10\n ),\n]\n\n@inline(never)\npublic func run_NibbleSort(_ n: Int) {\n let vRef: UInt64 = 0xfeedbba000000000\n let v: UInt64 = 0xbadbeef\n var c = NibbleCollection(v)\n\n for _ in 1...1_000*n {\n c.val = v\n c.sort()\n\n if c.val != vRef {\n break\n }\n }\n\n check(c.val == vRef)\n}\n\nstruct NibbleCollection {\n var val: UInt64\n init(_ val: UInt64) { self.val = val }\n}\n\nextension NibbleCollection: RandomAccessCollection, MutableCollection {\n typealias Index = UInt64\n var startIndex: UInt64 { return 0 }\n var endIndex: UInt64 { return 16 }\n\n subscript(idx: UInt64) -> UInt64 {\n get {\n return (val >> (idx*4)) & 0xf\n }\n set(n) {\n let mask = (0xf as UInt64) << (idx * 4)\n val &= ~mask\n val |= n << (idx * 4)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_NibbleSort.swift | cpp_apple_swift_benchmark_single-source_NibbleSort.swift | Swift | 1,019 | 0.95 | 0.037037 | 0.066667 | vue-tools | 473 | 2025-04-30T14:43:50.064818 | GPL-3.0 | false | 63740be01792e25a40f2d2d8d6558b80 |
//===--- NIOChannelPipeline.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// Mini benchmark implementing the gist of SwiftNIO's ChannelPipeline as\n// implemented by NIO 1 and NIO 2.[01]\nlet t: [BenchmarkCategory] = [.runtime, .refcount, .cpubench]\nlet n = 100\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "NIOChannelPipeline",\n runFunction: runBench,\n tags: t),\n]\n\npublic protocol EventHandler: class {\n func event(holder: Holder)\n}\n\nextension EventHandler {\n public func event(holder: Holder) {\n holder.fireEvent()\n }\n}\n\npublic final class Pipeline {\n var head: Holder? = nil\n\n public init() {}\n\n public func addHandler(_ handler: EventHandler) {\n if self.head == nil {\n self.head = Holder(handler)\n return\n }\n\n var node = self.head\n while node?.next != nil {\n node = node?.next\n }\n node?.next = Holder(handler)\n }\n\n public func fireEvent() {\n self.head!.invokeEvent()\n }\n}\n\npublic final class Holder {\n var next: Holder?\n let node: EventHandler\n\n init(_ node: EventHandler) {\n self.next = nil\n self.node = node\n }\n\n func invokeEvent() {\n self.node.event(holder: self)\n }\n\n @inline(never)\n public func fireEvent() {\n self.next?.invokeEvent()\n }\n}\n\npublic final class NoOpHandler: EventHandler {\n public init() {}\n}\n\npublic final class ConsumingHandler: EventHandler {\n var consumed = 0\n public init() {}\n public func event(holder: Holder) {\n self.consumed += 1\n }\n}\n\n@inline(never)\nfunc runBench(iterations: Int) {\n let pipeline = Pipeline()\n for _ in 0..<5 {\n pipeline.addHandler(NoOpHandler())\n }\n pipeline.addHandler(ConsumingHandler())\n\n for _ in 0 ..< iterations {\n for _ in 0 ..< 1000 {\n pipeline.fireEvent()\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_NIOChannelPipeline.swift | cpp_apple_swift_benchmark_single-source_NIOChannelPipeline.swift | Swift | 2,340 | 0.95 | 0.115385 | 0.151163 | awesome-app | 101 | 2024-04-22T14:30:17.247578 | GPL-3.0 | false | c5dba46de6b1d4c34774cd6be497870b |
//===--- NopDeinit.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// <rdar://problem/17838787>\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "NopDeinit",\n runFunction: run_NopDeinit,\n tags: [.regression],\n legacyFactor: 100)\n\nclass X<T : Comparable> {\n let deinitIters = 10000\n var elem: T\n init(_ x : T) {elem = x}\n deinit {\n for _ in 1...deinitIters {\n if (elem > elem) { }\n }\n }\n}\n\npublic func run_NopDeinit(_ n: Int) {\n for _ in 1...n {\n var arr :[X<Int>] = []\n let size = 5\n for i in 1...size { arr.append(X(i)) }\n arr.removeAll()\n check(arr.count == 0)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_NopDeinit.swift | cpp_apple_swift_benchmark_single-source_NopDeinit.swift | Swift | 1,084 | 0.95 | 0.166667 | 0.315789 | node-utils | 67 | 2024-11-21T21:30:34.820350 | BSD-3-Clause | false | 80cbdfc5ef0200bf1806e71b19ff4d34 |
//===--- NSDictionaryCastToSwift.swift ------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Performance benchmark for casting NSDictionary to Swift Dictionary\n// rdar://problem/18539730\n//\n// Description:\n// Create an NSDictionary instance and cast it to [String: NSObject].\nimport Foundation\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "NSDictionaryCastToSwift",\n runFunction: run_NSDictionaryCastToSwift,\n tags: [.validation, .api, .Dictionary, .bridging],\n legacyFactor: 10)\n\n@inline(never)\npublic func run_NSDictionaryCastToSwift(_ n: Int) {\n#if _runtime(_ObjC)\n let nsdict = NSDictionary()\n var swiftDict = [String: NSObject]()\n for _ in 1...1_000*n {\n swiftDict = nsdict as! [String: NSObject]\n if !swiftDict.isEmpty {\n break\n }\n }\n check(swiftDict.isEmpty)\n#endif\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_NSDictionaryCastToSwift.swift | cpp_apple_swift_benchmark_single-source_NSDictionaryCastToSwift.swift | Swift | 1,290 | 0.95 | 0.146341 | 0.473684 | vue-tools | 588 | 2023-12-22T18:55:06.474836 | Apache-2.0 | false | 48f66038771dd53854fa31fe42992102 |
//===--- NSStringConversion.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// <rdar://problem/19003201>\n#if canImport(Darwin)\n\nimport TestsUtils\nimport Foundation\n\nfileprivate var test:NSString = ""\nfileprivate var mutableTest = ""\n\npublic let benchmarks = [\n BenchmarkInfo(name: "NSStringConversion",\n runFunction: run_NSStringConversion,\n tags: [.validation, .api, .String, .bridging]),\n BenchmarkInfo(name: "NSStringConversion.UTF8",\n runFunction: run_NSStringConversion_nonASCII,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "tëst", encoding: String.Encoding.utf8.rawValue)! }),\n BenchmarkInfo(name: "NSStringConversion.Mutable",\n runFunction: run_NSMutableStringConversion,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSMutableString(cString: "test", encoding: String.Encoding.ascii.rawValue)! }),\n BenchmarkInfo(name: "NSStringConversion.Medium",\n runFunction: run_NSStringConversion_medium,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "aaaaaaaaaaaaaaa", encoding: String.Encoding.ascii.rawValue)! } ),\n BenchmarkInfo(name: "NSStringConversion.Long",\n runFunction: run_NSStringConversion_long,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "The quick brown fox jumps over the lazy dog", encoding: String.Encoding.ascii.rawValue)! } ),\n BenchmarkInfo(name: "NSStringConversion.LongUTF8",\n runFunction: run_NSStringConversion_longNonASCII,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "Thë qüick bröwn föx jumps over the lazy dög", encoding: String.Encoding.utf8.rawValue)! } ),\n BenchmarkInfo(name: "NSStringConversion.Rebridge",\n runFunction: run_NSStringConversion_rebridge,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "test", encoding: String.Encoding.ascii.rawValue)! }),\n BenchmarkInfo(name: "NSStringConversion.Rebridge.UTF8",\n runFunction: run_NSStringConversion_nonASCII_rebridge,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "tëst", encoding: String.Encoding.utf8.rawValue)! }),\n BenchmarkInfo(name: "NSStringConversion.Rebridge.Mutable",\n runFunction: run_NSMutableStringConversion_rebridge,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSMutableString(cString: "test", encoding: String.Encoding.ascii.rawValue)! }),\n BenchmarkInfo(name: "NSStringConversion.Rebridge.Medium",\n runFunction: run_NSStringConversion_medium_rebridge,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "aaaaaaaaaaaaaaa", encoding: String.Encoding.ascii.rawValue)! } ),\n BenchmarkInfo(name: "NSStringConversion.Rebridge.Long",\n runFunction: run_NSStringConversion_long_rebridge,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "The quick brown fox jumps over the lazy dog", encoding: String.Encoding.ascii.rawValue)! } ),\n BenchmarkInfo(name: "NSStringConversion.Rebridge.LongUTF8",\n runFunction: run_NSStringConversion_longNonASCII_rebridge,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { test = NSString(cString: "Thë qüick bröwn föx jumps over the lazy dög", encoding: String.Encoding.utf8.rawValue)! } ),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.UTF8",\n runFunction: run_NSStringConversion_nonASCIIMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "tëst" }),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.Medium",\n runFunction: run_NSStringConversion_mediumMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "aaaaaaaaaaaaaaa" } ),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.Long",\n runFunction: run_NSStringConversion_longMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "The quick brown fox jumps over the lazy dog" } ),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.LongUTF8",\n runFunction: run_NSStringConversion_longNonASCIIMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "Thë qüick bröwn föx jumps over the lazy dög" } ),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge",\n runFunction: run_NSStringConversion_rebridgeMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "test" }),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge.UTF8",\n runFunction: run_NSStringConversion_nonASCII_rebridgeMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "tëst" }),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge.Medium",\n runFunction: run_NSStringConversion_medium_rebridgeMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "aaaaaaaaaaaaaaa" } ),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge.Long",\n runFunction: run_NSStringConversion_long_rebridgeMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "The quick brown fox jumps over the lazy dog" } ),\n BenchmarkInfo(name: "NSStringConversion.MutableCopy.Rebridge.LongUTF8",\n runFunction: run_NSStringConversion_longNonASCII_rebridgeMutable,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: { mutableTest = "Thë qüick bröwn föx jumps over the lazy dög" } ),\n BenchmarkInfo(name: "NSStringConversion.InlineBuffer.UTF8",\n runFunction: run_NSStringConversion_inlineBuffer,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: {\n mutableTest = Array(repeating: "제10회 유니코드 국제 회의가 1997년 3월 10일부터 12일까지 독일의 마인즈에서 열립니다. 지금 등록하십시오. 이 회의에서는 업계 전반의 전문가들이 함께 모여 다음과 같은 분야를 다룹니다. - 인터넷과 유니코드, 국제화와 지역화, 운영 체제와 응용 프로그램에서 유니코드의 구현, 글꼴, 문자 배열, 다국어 컴퓨팅.세계를 향한 대화, 유니코드로 하십시오. 제10회 유니코드 국제 회의가 1997년 3월 10일부터 12일까지 독일의 마인즈에서 열립니다. 지금 등록하십시오. 이 회의에서는 업계 전반의 전문가들이 함께 모여 다음과 같은 분야를 다룹니다. 세계를 향한 대화, 유니코드로 하십시오.", count: 256).joined(separator: "")\n }\n ),\n BenchmarkInfo(name: "NSStringConversion.InlineBuffer.ASCII",\n runFunction: run_NSStringConversion_inlineBuffer,\n tags: [.validation, .api, .String, .bridging],\n setUpFunction: {\n mutableTest = Array(repeating: "The 10th Unicode International Conference will be held from March 10 to 12, 1997 in Mainz, Germany. Register now. The conference brings together experts from across the industry, covering areas such as: - Internet and Unicode, internationalization and localization, implementation of Unicode in operating systems and applications, fonts, character arrays, multilingual computing. Dialogue to the world, do Unicode. The 10th Unicode International Conference will be held from March 10 to 12, 1997 in Mainz, Germany. Register now. The conference brings together experts from across the industry, covering areas such as: Dialogue to the world, do it in Unicode.", count: 256).joined(separator: "")\n }\n )\n]\n\npublic func run_NSStringConversion(_ n: Int) {\nlet test:NSString = NSString(cString: "test", encoding: String.Encoding.ascii.rawValue)!\n for _ in 1...n * 10000 {\n //Doesn't test accessing the String contents to avoid changing historical benchmark numbers\n blackHole(identity(test) as String)\n }\n}\n\nfileprivate func innerLoop(_ str: NSString, _ n: Int, _ scale: Int = 5000) {\n for _ in 1...n * scale {\n for char in (identity(str) as String).utf8 {\n blackHole(char)\n }\n }\n}\n\npublic func run_NSStringConversion_nonASCII(_ n: Int) {\n innerLoop(test, n, 2500)\n}\n\npublic func run_NSMutableStringConversion(_ n: Int) {\n innerLoop(test, n)\n}\n\npublic func run_NSStringConversion_medium(_ n: Int) {\n innerLoop(test, n, 1000)\n}\n\npublic func run_NSStringConversion_long(_ n: Int) {\n innerLoop(test, n, 1000)\n}\n\npublic func run_NSStringConversion_longNonASCII(_ n: Int) {\n innerLoop(test, n, 300)\n}\n\nfileprivate func innerMutableLoop(_ str: String, _ n: Int, _ scale: Int = 5000) {\n for _ in 1...n * scale {\n let copy = (str as NSString).mutableCopy() as! NSMutableString\n for char in (identity(copy) as String).utf8 {\n blackHole(char)\n }\n }\n}\n\npublic func run_NSStringConversion_nonASCIIMutable(_ n: Int) {\n innerMutableLoop(mutableTest, n, 500)\n}\n\npublic func run_NSStringConversion_mediumMutable(_ n: Int) {\n innerMutableLoop(mutableTest, n, 500)\n}\n\npublic func run_NSStringConversion_longMutable(_ n: Int) {\n innerMutableLoop(mutableTest, n, 250)\n}\n\npublic func run_NSStringConversion_longNonASCIIMutable(_ n: Int) {\n innerMutableLoop(mutableTest, n, 150)\n}\n\nfileprivate func innerRebridge(_ str: NSString, _ n: Int, _ scale: Int = 5000) {\n for _ in 1...n * scale {\n let bridged = identity(str) as String\n blackHole(bridged)\n blackHole(bridged as NSString)\n }\n}\n\npublic func run_NSStringConversion_rebridge(_ n: Int) {\n innerRebridge(test, n, 2500)\n}\n\npublic func run_NSStringConversion_nonASCII_rebridge(_ n: Int) {\n innerRebridge(test, n, 2500)\n}\n\npublic func run_NSMutableStringConversion_rebridge(_ n: Int) {\n innerRebridge(test, n)\n}\n\npublic func run_NSStringConversion_medium_rebridge(_ n: Int) {\n innerRebridge(test, n, 1000)\n}\n\npublic func run_NSStringConversion_long_rebridge(_ n: Int) {\n innerRebridge(test, n, 1000)\n}\n\npublic func run_NSStringConversion_longNonASCII_rebridge(_ n: Int) {\n innerRebridge(test, n, 300)\n}\n\nfileprivate func innerMutableRebridge(_ str: String, _ n: Int, _ scale: Int = 5000) {\n for _ in 1...n * scale {\n let copy = (str as NSString).mutableCopy() as! NSMutableString\n let bridged = identity(copy) as String\n blackHole(bridged)\n blackHole(bridged as NSString)\n }\n}\n\npublic func run_NSStringConversion_rebridgeMutable(_ n: Int) {\n innerMutableRebridge(mutableTest, n, 1000)\n}\n\npublic func run_NSStringConversion_nonASCII_rebridgeMutable(_ n: Int) {\n innerMutableRebridge(mutableTest, n, 500)\n}\n\npublic func run_NSStringConversion_medium_rebridgeMutable(_ n: Int) {\n innerMutableRebridge(mutableTest, n, 500)\n}\n\npublic func run_NSStringConversion_long_rebridgeMutable(_ n: Int) {\n innerMutableRebridge(mutableTest, n, 500)\n}\n\npublic func run_NSStringConversion_longNonASCII_rebridgeMutable(_ n: Int) {\n innerMutableRebridge(mutableTest, n, 300)\n}\n\npublic func run_NSStringConversion_inlineBuffer(_ n: Int) {\n withUnsafeTemporaryAllocation(\n of: CFStringInlineBuffer.self,\n capacity: 1\n ) { bufferPtr in\n let buffer = bufferPtr.baseAddress!\n for _ in 0 ..< n {\n var result = UInt64(0)\n let bridged = mutableTest as NSString as CFString\n let len = CFStringGetLength(bridged)\n CFStringInitInlineBuffer(bridged, buffer, CFRangeMake(0, len))\n for i in 0 ..< CFStringGetLength(bridged) {\n let char = CFStringGetCharacterFromInlineBuffer(buffer, i)\n result += UInt64(char)\n }\n blackHole(result)\n }\n }\n}\n\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_NSStringConversion.swift | cpp_apple_swift_benchmark_single-source_NSStringConversion.swift | Swift | 12,881 | 0.95 | 0.045455 | 0.064378 | python-kit | 873 | 2024-12-24T23:46:33.578982 | MIT | false | 5685da24c26d51f2e0e883077115b52f |
//===--- ObjectAllocation.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// This test checks the performance of allocations.\n// 53% _swift_release_dealloc\n// 30% _swift_alloc_object\n// 10% retain/release\npublic let benchmarks =\n BenchmarkInfo(\n name: "ObjectAllocation",\n runFunction: run_ObjectAllocation,\n tags: [.runtime, .cpubench]\n )\n\nfinal class XX {\n var xx: Int\n\n init(_ x: Int) {\n xx = x\n }\n}\n\nfinal class TreeNode {\n let left: XX\n let right: XX\n\n init(_ l: XX, _ r: XX) {\n left = l\n right = r\n }\n}\n\nfinal class LinkedNode {\n var next: LinkedNode?\n var xx: Int\n\n init(_ x: Int, _ n: LinkedNode?) {\n xx = x\n next = n\n }\n}\n\n@inline(never)\nfunc getInt(_ x: XX) -> Int {\n return x.xx\n}\n\n@inline(never)\nfunc testSingleObject() -> Int {\n var s = 0\n for i in 0..<1000 {\n let x = XX(i)\n s += getInt(x)\n }\n return s\n}\n\n@inline(never)\nfunc addInts(_ t: TreeNode) -> Int {\n return t.left.xx + t.right.xx\n}\n\n@inline(never)\nfunc testTree() -> Int {\n var s = 0\n for i in 0..<300 {\n let t = TreeNode(XX(i), XX(i + 1))\n s += addInts(t)\n }\n return s\n}\n\n@inline(never)\nfunc addAllInts(_ n: LinkedNode) -> Int {\n var s = 0\n var iter: LinkedNode? = n\n while let iter2 = iter {\n s += iter2.xx\n iter = iter2.next\n }\n return s\n}\n\n@inline(never)\nfunc testList() -> Int {\n var s = 0\n for i in 0..<250 {\n let l = LinkedNode(i, LinkedNode(27, LinkedNode(42, nil)))\n s += addAllInts(l)\n }\n return s\n}\n\n@inline(never)\nfunc identity(_ x: Int) -> Int {\n return x\n}\n\n@inline(never)\nfunc testArray() -> Int {\n var s = 0\n for _ in 0..<1000 {\n for i in [0, 1, 2] {\n s += identity(i)\n }\n }\n return s\n}\n\n@inline(never)\npublic func run_ObjectAllocation(_ n: Int) {\n\n var singleObjectResult = 0\n var treeResult = 0\n var listResult = 0\n var arrayResult = 0\n\n for _ in 0..<n {\n singleObjectResult = testSingleObject()\n treeResult = testTree()\n listResult = testList()\n arrayResult = testArray()\n }\n\n check(singleObjectResult == 499500)\n check(treeResult == 90000)\n check(listResult == 48375)\n check(arrayResult == 3000)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ObjectAllocation.swift | cpp_apple_swift_benchmark_single-source_ObjectAllocation.swift | Swift | 2,576 | 0.95 | 0.085714 | 0.125 | node-utils | 530 | 2024-09-05T20:28:45.669609 | BSD-3-Clause | false | 30bf57b5d9a9815b517cb428edad9494 |
//===--- ObjectiveCBridging.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Foundation\n\nlet t: [BenchmarkCategory] = [.validation, .bridging]\nlet ts: [BenchmarkCategory] = [.validation, .bridging, .String]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSString",\n runFunction: run_ObjectiveCBridgeFromNSString, tags: t,\n legacyFactor: 5),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSStringForced",\n runFunction: run_ObjectiveCBridgeFromNSStringForced, tags: t,\n legacyFactor: 5),\n BenchmarkInfo(name: "ObjectiveCBridgeToNSString",\n runFunction: run_ObjectiveCBridgeToNSString, tags: t),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSArrayAnyObject",\n runFunction: run_ObjectiveCBridgeFromNSArrayAnyObject, tags: t,\n legacyFactor: 100),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSArrayAnyObjectForced",\n runFunction: run_ObjectiveCBridgeFromNSArrayAnyObjectForced, tags: t,\n legacyFactor: 20),\n BenchmarkInfo(name: "ObjectiveCBridgeToNSArray",\n runFunction: run_ObjectiveCBridgeToNSArray, tags: t,\n legacyFactor: 50),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSArrayAnyObjectToString",\n runFunction: run_ObjectiveCBridgeFromNSArrayAnyObjectToString, tags: ts,\n legacyFactor: 100),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSArrayAnyObjectToStringForced",\n runFunction: run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced,\n tags: ts, legacyFactor: 200),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSDictionaryAnyObject",\n runFunction: run_ObjectiveCBridgeFromNSDictionaryAnyObject, tags: t,\n legacyFactor: 100),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSDictionaryAnyObjectForced",\n runFunction: run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced, tags: t,\n legacyFactor: 50),\n BenchmarkInfo(name: "ObjectiveCBridgeToNSDictionary",\n runFunction: run_ObjectiveCBridgeToNSDictionary, tags: t,\n legacyFactor: 50),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSDictionaryAnyObjectToString",\n runFunction: run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString,\n tags: ts, legacyFactor: 500),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced",\n runFunction: run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced,\n tags: ts, legacyFactor: 500),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSSetAnyObject",\n runFunction: run_ObjectiveCBridgeFromNSSetAnyObject, tags: t,\n legacyFactor: 200),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSSetAnyObjectForced",\n runFunction: run_ObjectiveCBridgeFromNSSetAnyObjectForced, tags: t,\n legacyFactor: 20),\n BenchmarkInfo(name: "ObjectiveCBridgeToNSSet",\n runFunction: run_ObjectiveCBridgeToNSSet, tags: t,\n legacyFactor: 50),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSSetAnyObjectToString",\n runFunction: run_ObjectiveCBridgeFromNSSetAnyObjectToString, tags: ts,\n legacyFactor: 500),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSSetAnyObjectToStringForced",\n runFunction: run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced, tags: ts,\n legacyFactor: 500),\n BenchmarkInfo(name: "ObjectiveCBridgeFromNSDateComponents",\n runFunction: run_ObjectiveCBridgeFromNSDateComponents, tags: t,\n setUpFunction: setup_dateComponents),\n BenchmarkInfo(name: "ObjectiveCBridgeASCIIStringFromFile",\n runFunction: run_ASCIIStringFromFile, tags: ts,\n setUpFunction: setup_ASCIIStringFromFile),\n BenchmarkInfo(name: "UnicodeStringFromCodable",\n runFunction: run_UnicodeStringFromCodable, tags: ts,\n setUpFunction: setup_UnicodeStringFromCodable),\n BenchmarkInfo(name: "NSArray.bridged.objectAtIndex",\n runFunction: run_BridgedNSArrayObjectAtIndex, tags: t,\n setUpFunction: setup_bridgedArrays),\n BenchmarkInfo(name: "NSArray.bridged.mutableCopy.objectAtIndex",\n runFunction: run_BridgedNSArrayMutableCopyObjectAtIndex, tags: t,\n setUpFunction: setup_bridgedArrays),\n BenchmarkInfo(name: "NSArray.nonbridged.objectAtIndex",\n runFunction: run_RealNSArrayObjectAtIndex, tags: t,\n setUpFunction: setup_bridgedArrays),\n BenchmarkInfo(name: "NSArray.nonbridged.mutableCopy.objectAtIndex",\n runFunction: run_RealNSArrayMutableCopyObjectAtIndex, tags: t,\n setUpFunction: setup_bridgedArrays),\n BenchmarkInfo(name: "NSArray.bridged.bufferAccess",\n runFunction: run_BridgedNSArrayBufferAccess, tags: t,\n setUpFunction: setup_bridgedArrays),\n BenchmarkInfo(name: "NSArray.bridged.repeatedBufferAccess",\n runFunction: run_BridgedNSArrayRepeatedBufferAccess, tags: t,\n setUpFunction: setup_bridgedArrays),\n]\n\n#if _runtime(_ObjC)\n@inline(never)\npublic func forcedCast<NS, T>(_ ns: NS) -> T {\n return ns as! T\n}\n\n@inline(never)\npublic func conditionalCast<NS, T>(_ ns: NS) -> T? {\n return ns as? T\n}\n#endif\n\n\n// === String === //\n\n#if _runtime(_ObjC)\nfunc createNSString() -> NSString {\n return NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n}\n\n@inline(never)\nfunc testObjectiveCBridgeFromNSString() {\n let nsString = createNSString()\n\n var s: String?\n for _ in 0 ..< 2_000 {\n // Call _conditionallyBridgeFromObjectiveC.\n let n : String? = conditionalCast(nsString)\n if n != nil {\n s = n!\n }\n }\n check(s != nil && s == "NSString that does not fit in tagged pointer")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSString()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSStringForced() {\n let nsString = createNSString()\n\n var s: String?\n for _ in 0 ..< 2_000 {\n // Call _forceBridgeFromObjectiveC\n s = forcedCast(nsString)\n }\n check(s != nil && s == "NSString that does not fit in tagged pointer")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSStringForced(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSStringForced()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeToNSString() {\n let nativeString = "Native"\n\n var s: NSString?\n for _ in 0 ..< 10_000 {\n // Call _BridgedToObjectiveC\n s = nativeString as NSString\n }\n check(s != nil && s == "Native")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeToNSString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeToNSString()\n }\n }\n#endif\n}\n\n// === Array === //\n\n#if _runtime(_ObjC)\nfunc createNSArray() -> NSArray {\n let nsMutableArray = NSMutableArray()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n nsMutableArray.add(nsString)\n return nsMutableArray.copy() as! NSArray\n}\n\n@inline(never)\nfunc testObjectiveCBridgeFromNSArrayAnyObject() {\n let nsArray = createNSArray()\n\n var nativeString : String?\n for _ in 0 ..< 100 {\n if let nativeArray : [NSString] = conditionalCast(nsArray) {\n nativeString = forcedCast(nativeArray[0])\n }\n }\n check(nativeString != nil && nativeString! == "NSString that does not fit in tagged pointer")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSArrayAnyObject(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSArrayAnyObject()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSArrayAnyObjectForced() {\n let nsArray = createNSArray()\n\n var nativeString : String?\n for _ in 0 ..< 500 {\n let nativeArray : [NSString] = forcedCast(nsArray)\n nativeString = forcedCast(nativeArray[0])\n }\n check(nativeString != nil && nativeString! == "NSString that does not fit in tagged pointer")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSArrayAnyObjectForced(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSArrayAnyObjectForced()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeToNSArray() {\n let nativeArray = ["abcde", "abcde", "abcde", "abcde", "abcde",\n "abcde", "abcde", "abcde", "abcde", "abcde"]\n\n var nsString : Any?\n for _ in 0 ..< 200 {\n let nsArray = nativeArray as NSArray\n nsString = nsArray.object(at: 0)\n }\n check(nsString != nil && (nsString! as! NSString).isEqual("abcde"))\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeToNSArray(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeToNSArray()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSArrayAnyObjectToString() {\n let nsArray = createNSArray()\n\n var nativeString : String?\n for _ in 0 ..< 100 {\n if let nativeArray : [String] = conditionalCast(nsArray) {\n nativeString = nativeArray[0]\n }\n }\n check(nativeString != nil && nativeString == "NSString that does not fit in tagged pointer")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSArrayAnyObjectToString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSArrayAnyObjectToString()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSArrayAnyObjectToStringForced() {\n let nsArray = createNSArray()\n\n var nativeString : String?\n for _ in 0 ..< 50 {\n let nativeArray : [String] = forcedCast(nsArray)\n nativeString = nativeArray[0]\n }\n check(nativeString != nil && nativeString == "NSString that does not fit in tagged pointer")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSArrayAnyObjectToStringForced(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSArrayAnyObjectToStringForced()\n }\n }\n#endif\n}\n\n// === Dictionary === //\n\n#if _runtime(_ObjC)\nfunc createNSDictionary() -> NSDictionary {\n let nsMutableDictionary = NSMutableDictionary()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n let nsString2 = NSString(cString: "NSString that does not fit in tagged pointer 2", encoding: String.Encoding.utf8.rawValue)!\n let nsString3 = NSString(cString: "NSString that does not fit in tagged pointer 3", encoding: String.Encoding.utf8.rawValue)!\n let nsString4 = NSString(cString: "NSString that does not fit in tagged pointer 4", encoding: String.Encoding.utf8.rawValue)!\n let nsString5 = NSString(cString: "NSString that does not fit in tagged pointer 5", encoding: String.Encoding.utf8.rawValue)!\n let nsString6 = NSString(cString: "NSString that does not fit in tagged pointer 6", encoding: String.Encoding.utf8.rawValue)!\n let nsString7 = NSString(cString: "NSString that does not fit in tagged pointer 7", encoding: String.Encoding.utf8.rawValue)!\n let nsString8 = NSString(cString: "NSString that does not fit in tagged pointer 8", encoding: String.Encoding.utf8.rawValue)!\n let nsString9 = NSString(cString: "NSString that does not fit in tagged pointer 9", encoding: String.Encoding.utf8.rawValue)!\n let nsString10 = NSString(cString: "NSString that does not fit in tagged pointer 10", encoding: String.Encoding.utf8.rawValue)!\n nsMutableDictionary.setObject(1, forKey: nsString)\n nsMutableDictionary.setObject(2, forKey: nsString2)\n nsMutableDictionary.setObject(3, forKey: nsString3)\n nsMutableDictionary.setObject(4, forKey: nsString4)\n nsMutableDictionary.setObject(5, forKey: nsString5)\n nsMutableDictionary.setObject(6, forKey: nsString6)\n nsMutableDictionary.setObject(7, forKey: nsString7)\n nsMutableDictionary.setObject(8, forKey: nsString8)\n nsMutableDictionary.setObject(9, forKey: nsString9)\n nsMutableDictionary.setObject(10, forKey: nsString10)\n\n return nsMutableDictionary.copy() as! NSDictionary\n}\n\n@inline(never)\nfunc testObjectiveCBridgeFromNSDictionaryAnyObject() {\n let nsDictionary = createNSDictionary()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n\n var nativeInt : Int?\n for _ in 0 ..< 100 {\n if let nativeDictionary : [NSString : NSNumber] = conditionalCast(nsDictionary) {\n nativeInt = forcedCast(nativeDictionary[nsString])\n }\n }\n check(nativeInt != nil && nativeInt == 1)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSDictionaryAnyObject(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSDictionaryAnyObject()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSDictionaryAnyObjectForced() {\n let nsDictionary = createNSDictionary()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n\n var nativeInt : Int?\n for _ in 0 ..< 200 {\n if let nativeDictionary : [NSString : NSNumber] = forcedCast(nsDictionary) {\n nativeInt = forcedCast(nativeDictionary[nsString])\n }\n }\n check(nativeInt != nil && nativeInt == 1)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSDictionaryAnyObjectForced(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSDictionaryAnyObjectForced()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeToNSDictionary() {\n let nativeDictionary = ["abcde1": 1, "abcde2": 2, "abcde3": 3, "abcde4": 4,\n "abcde5": 5, "abcde6": 6, "abcde7": 7, "abcde8": 8, "abcde9": 9,\n "abcde10": 10]\n let key = "abcde1" as NSString\n\n var nsNumber : Any?\n for _ in 0 ..< 200 {\n let nsDict = nativeDictionary as NSDictionary\n nsNumber = nsDict.object(forKey: key)\n }\n check(nsNumber != nil && (nsNumber as! Int) == 1)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeToNSDictionary(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeToNSDictionary()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSDictionaryAnyObjectToString() {\n let nsDictionary = createNSDictionary()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n let nativeString = nsString as String\n\n var nativeInt : Int?\n for _ in 0 ..< 20 {\n if let nativeDictionary : [String : Int] = conditionalCast(nsDictionary) {\n nativeInt = nativeDictionary[nativeString]\n }\n }\n check(nativeInt != nil && nativeInt == 1)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSDictionaryAnyObjectToString()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced() {\n let nsDictionary = createNSDictionary()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n let nativeString = nsString as String\n\n var nativeInt : Int?\n for _ in 0 ..< 20 {\n if let nativeDictionary : [String : Int] = forcedCast(nsDictionary) {\n nativeInt = nativeDictionary[nativeString]\n }\n }\n check(nativeInt != nil && nativeInt == 1)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSDictionaryAnyObjectToStringForced()\n }\n }\n#endif\n}\n\n// === Set === //\n\n#if _runtime(_ObjC)\nfunc createNSSet() -> NSSet {\n let nsMutableSet = NSMutableSet()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n let nsString2 = NSString(cString: "NSString that does not fit in tagged pointer 2", encoding: String.Encoding.utf8.rawValue)!\n let nsString3 = NSString(cString: "NSString that does not fit in tagged pointer 3", encoding: String.Encoding.utf8.rawValue)!\n let nsString4 = NSString(cString: "NSString that does not fit in tagged pointer 4", encoding: String.Encoding.utf8.rawValue)!\n let nsString5 = NSString(cString: "NSString that does not fit in tagged pointer 5", encoding: String.Encoding.utf8.rawValue)!\n let nsString6 = NSString(cString: "NSString that does not fit in tagged pointer 6", encoding: String.Encoding.utf8.rawValue)!\n let nsString7 = NSString(cString: "NSString that does not fit in tagged pointer 7", encoding: String.Encoding.utf8.rawValue)!\n let nsString8 = NSString(cString: "NSString that does not fit in tagged pointer 8", encoding: String.Encoding.utf8.rawValue)!\n let nsString9 = NSString(cString: "NSString that does not fit in tagged pointer 9", encoding: String.Encoding.utf8.rawValue)!\n let nsString10 = NSString(cString: "NSString that does not fit in tagged pointer 10", encoding: String.Encoding.utf8.rawValue)!\n nsMutableSet.add(nsString)\n nsMutableSet.add(nsString2)\n nsMutableSet.add(nsString3)\n nsMutableSet.add(nsString4)\n nsMutableSet.add(nsString5)\n nsMutableSet.add(nsString6)\n nsMutableSet.add(nsString7)\n nsMutableSet.add(nsString8)\n nsMutableSet.add(nsString9)\n nsMutableSet.add(nsString10)\n\n return nsMutableSet.copy() as! NSSet\n}\n\n\n@inline(never)\nfunc testObjectiveCBridgeFromNSSetAnyObject() {\n let nsSet = createNSSet()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n\n var result : Bool?\n for _ in 0 ..< 50 {\n if let nativeSet : Set<NSString> = conditionalCast(nsSet) {\n result = nativeSet.contains(nsString)\n }\n }\n check(result != nil && result!)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSSetAnyObject(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSSetAnyObject()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSSetAnyObjectForced() {\n let nsSet = createNSSet()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n\n var result : Bool?\n for _ in 0 ..< 500 {\n if let nativeSet : Set<NSString> = forcedCast(nsSet) {\n result = nativeSet.contains(nsString)\n }\n }\n check(result != nil && result!)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSSetAnyObjectForced(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSSetAnyObjectForced()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeToNSSet() {\n let nativeSet = Set<String>(["abcde1", "abcde2", "abcde3", "abcde4", "abcde5",\n "abcde6", "abcde7", "abcde8", "abcde9", "abcde10"])\n let key = "abcde1" as NSString\n\n var nsString : Any?\n for _ in 0 ..< 200 {\n let nsDict = nativeSet as NSSet\n nsString = nsDict.member(key)\n }\n check(nsString != nil && (nsString as! String) == "abcde1")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeToNSSet(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeToNSSet()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSSetAnyObjectToString() {\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n let nativeString = nsString as String\n let nsSet = createNSSet()\n\n var result : Bool?\n for _ in 0 ..< 20 {\n if let nativeSet : Set<String> = conditionalCast(nsSet) {\n result = nativeSet.contains(nativeString)\n }\n }\n check(result != nil && result!)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSSetAnyObjectToString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSSetAnyObjectToString()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeFromNSSetAnyObjectToStringForced() {\n let nsSet = createNSSet()\n let nsString = NSString(cString: "NSString that does not fit in tagged pointer", encoding: String.Encoding.utf8.rawValue)!\n let nativeString = nsString as String\n\n var result : Bool?\n for _ in 0 ..< 20 {\n if let nativeSet : Set<String> = forcedCast(nsSet) {\n result = nativeSet.contains(nativeString)\n }\n }\n check(result != nil && result!)\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSSetAnyObjectToStringForced(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeFromNSSetAnyObjectToStringForced()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n\n//translated directly from an objc part of the original testcase\n@objc class DictionaryContainer : NSObject {\n @objc var _dictionary:NSDictionary\n\n //simulate an objc property being imported via bridging\n @objc var dictionary:Dictionary<DateComponents, String> {\n @inline(never)\n get {\n return _dictionary as! Dictionary<DateComponents, String>\n }\n }\n\n override init() {\n _dictionary = NSDictionary()\n super.init()\n let dict = NSMutableDictionary()\n let calendar = NSCalendar(calendarIdentifier: .gregorian)!\n let now = Date()\n for day in 0..<36 {\n let date = calendar.date(byAdding: .day, value: -day, to: now, options: NSCalendar.Options())\n let components = calendar.components([.year, .month, .day], from: date!)\n dict[components as NSDateComponents] = "TESTING"\n }\n _dictionary = NSDictionary(dictionary: dict)\n }\n}\n\nvar componentsContainer: DictionaryContainer? = nil\nvar componentsArray:[DateComponents]? = nil\n#endif\n\npublic func setup_dateComponents() {\n #if _runtime(_ObjC)\n componentsContainer = DictionaryContainer()\n let now = Date()\n let calendar = Calendar(identifier: .gregorian)\n componentsArray = (0..<10).compactMap { (day) -> DateComponents? in\n guard let date = calendar.date(byAdding: .day, value: -day, to: now) else {\n return nil\n }\n\n return calendar.dateComponents([.year, .month, .day], from: date)\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeFromNSDateComponents(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n for components in componentsArray! {\n let _ = componentsContainer!.dictionary[components]\n }\n }\n #endif\n}\n\nvar asciiStringFromFile: String? = nil\npublic func setup_ASCIIStringFromFile() {\n #if _runtime(_ObjC)\n let url:URL\n if #available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {\n url = FileManager.default.temporaryDirectory.appendingPathComponent(\n "sphinx.txt"\n )\n } else {\n url = URL(fileURLWithPath: "/tmp/sphinx.txt")\n }\n var str = "Sphinx of black quartz judge my vow"\n str = Array(repeating: str, count: 100).joined()\n try? str.write(\n to: url,\n atomically: true,\n encoding: .ascii\n )\n asciiStringFromFile = try! String(contentsOf: url, encoding: .ascii)\n #endif\n}\n\n@inline(never)\npublic func run_ASCIIStringFromFile(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n blackHole((asciiStringFromFile! + "").utf8.count)\n }\n #endif\n}\n\nvar unicodeStringFromCodable:String? = nil\nvar unicodeStringFromCodableDict = [String:Void]()\npublic func setup_UnicodeStringFromCodable() {\n do {\n let jsonString = "[\(String(reflecting: "Nice string which works rather slöw."))]"\n \n let decoded = try JSONDecoder().decode([String].self, from: Data(jsonString.utf8))\n let reEncoded = try JSONEncoder().encode(decoded)\n let desc = try JSONDecoder().decode([String].self, from: reEncoded)\n \n unicodeStringFromCodable = desc[0]\n } catch (_) {\n \n }\n}\n\n@inline(never)\npublic func run_UnicodeStringFromCodable(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n for _ in 0..<100 {\n unicodeStringFromCodableDict[identity(unicodeStringFromCodable!)] = ()\n }\n }\n #endif\n}\n\n#if _runtime(_ObjC)\nvar bridgedArray:NSArray! = nil\nvar bridgedArrayMutableCopy:NSMutableArray! = nil\nvar nsArray:NSArray! = nil\nvar nsArrayMutableCopy:NSMutableArray! = nil\n#endif\n\npublic func setup_bridgedArrays() {\n #if _runtime(_ObjC)\n var arr = Array(repeating: NSObject(), count: 100) as [AnyObject]\n bridgedArray = arr as NSArray\n bridgedArrayMutableCopy = (bridgedArray.mutableCopy() as! NSMutableArray)\n nsArray = NSArray(objects: &arr, count: 100)\n nsArrayMutableCopy = (nsArray.mutableCopy() as! NSMutableArray)\n #endif\n}\n\n@inline(never)\npublic func run_BridgedNSArrayObjectAtIndex(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n * 50 {\n for i in 0..<100 {\n blackHole(bridgedArray[i])\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_BridgedNSArrayBufferAccess(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n for i in 0..<1000 {\n let tmp = nsArray as! [NSObject]\n blackHole(tmp)\n blackHole(tmp.withContiguousStorageIfAvailable {\n $0[0]\n })\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_BridgedNSArrayRepeatedBufferAccess(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n let tmp = nsArray as! [NSObject]\n blackHole(tmp)\n for i in 0..<1000 {\n blackHole(tmp.withContiguousStorageIfAvailable {\n $0[0]\n })\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_BridgedNSArrayMutableCopyObjectAtIndex(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n * 100 {\n for i in 0..<100 {\n blackHole(bridgedArrayMutableCopy[i])\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_RealNSArrayObjectAtIndex(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n * 100 {\n for i in 0..<100 {\n blackHole(nsArray[i])\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_RealNSArrayMutableCopyObjectAtIndex(_ n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n * 100 {\n for i in 0..<100 {\n blackHole(nsArrayMutableCopy[i])\n }\n }\n #endif\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ObjectiveCBridging.swift | cpp_apple_swift_benchmark_single-source_ObjectiveCBridging.swift | Swift | 26,805 | 0.95 | 0.142373 | 0.15443 | awesome-app | 827 | 2025-05-16T13:07:28.217986 | GPL-3.0 | false | f1c78d054a6426fa31f443be44a99459 |
//===--- ObjectiveCBridgingStubs.swift ------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Foundation\n#if _runtime(_ObjC)\nimport ObjectiveCTests\n#endif\n\nlet t: [BenchmarkCategory] = [.validation, .bridging]\nlet ts: [BenchmarkCategory] = [.validation, .String, .bridging]\nlet bs: [BenchmarkCategory] = [.String, .bridging]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "ObjectiveCBridgeStubDataAppend",\n runFunction: run_ObjectiveCBridgeStubDataAppend, tags: t,\n legacyFactor: 20),\n BenchmarkInfo(name: "ObjectiveCBridgeStubDateAccess",\n runFunction: run_ObjectiveCBridgeStubDateAccess, tags: t),\n BenchmarkInfo(name: "ObjectiveCBridgeStubDateMutation",\n runFunction: run_ObjectiveCBridgeStubDateMutation, tags: t),\n BenchmarkInfo(name: "ObjectiveCBridgeStubFromArrayOfNSString2",\n runFunction: run_ObjectiveCBridgeStubFromArrayOfNSString, tags: t,\n legacyFactor: 10),\n BenchmarkInfo(name: "ObjectiveCBridgeStubFromNSDate",\n runFunction: run_ObjectiveCBridgeStubFromNSDate, tags: t,\n legacyFactor: 10),\n BenchmarkInfo(name: "ObjectiveCBridgeStubFromNSString",\n runFunction: run_ObjectiveCBridgeStubFromNSString, tags: t),\n BenchmarkInfo(name: "ObjectiveCBridgeStubToArrayOfNSString2",\n runFunction: run_ObjectiveCBridgeStubToArrayOfNSString, tags: t,\n legacyFactor: 20),\n BenchmarkInfo(name: "ObjectiveCBridgeStubToNSDate2",\n runFunction: run_ObjectiveCBridgeStubToNSDate, tags: t,\n legacyFactor: 10),\n BenchmarkInfo(name: "ObjectiveCBridgeStubToNSString",\n runFunction: run_ObjectiveCBridgeStubToNSString, tags: t,\n legacyFactor: 10),\n BenchmarkInfo(name: "ObjectiveCBridgeStubURLAppendPath2",\n runFunction: run_ObjectiveCBridgeStubURLAppendPath, tags: t,\n legacyFactor: 10),\n BenchmarkInfo(name: "ObjectiveCBridgeStringIsEqual",\n runFunction: run_ObjectiveCBridgeStringIsEqual, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringIsEqual2",\n runFunction: run_ObjectiveCBridgeStringIsEqual2, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringIsEqualAllSwift",\n runFunction: run_ObjectiveCBridgeStringIsEqualAllSwift, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringCompare",\n runFunction: run_ObjectiveCBridgeStringCompare, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringCompare2",\n runFunction: run_ObjectiveCBridgeStringCompare2, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringGetASCIIContents",\n runFunction: run_ObjectiveCBridgeStringGetASCIIContents, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringGetUTF8Contents",\n runFunction: run_ObjectiveCBridgeStringGetUTF8Contents, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringRangeOfString", //should be BridgeString.find.mixed\n runFunction: run_ObjectiveCBridgeStringRangeOfString, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "BridgeString.find.native",\n runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwift, tags: bs,\n setUpFunction: setup_SpecificRangeOfStringBridging),\n BenchmarkInfo(name: "BridgeString.find.native.nonASCII",\n runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwiftNonASCII, tags: bs,\n setUpFunction: setup_SpecificRangeOfStringBridging),\n BenchmarkInfo(name: "BridgeString.find.native.long",\n runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystack, tags: bs,\n setUpFunction: setup_SpecificRangeOfStringBridging),\n BenchmarkInfo(name: "BridgeString.find.native.longBoth",\n runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystackLongNeedle, tags: bs,\n setUpFunction: setup_SpecificRangeOfStringBridging),\n BenchmarkInfo(name: "BridgeString.find.native.longNonASCII",\n runFunction: run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystackNonASCII, tags: bs,\n setUpFunction: setup_SpecificRangeOfStringBridging),\n BenchmarkInfo(name: "ObjectiveCBridgeStringHash",\n runFunction: run_ObjectiveCBridgeStringHash, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringUTF8String",\n runFunction: run_ObjectiveCBridgeStringUTF8String, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n BenchmarkInfo(name: "ObjectiveCBridgeStringCStringUsingEncoding",\n runFunction: run_ObjectiveCBridgeStringCStringUsingEncoding, tags: ts,\n setUpFunction: setup_StringBridgeBenchmark),\n]\n\nvar b:BridgeTester! = nil\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubFromNSString() {\n let b = BridgeTester()\n var str = ""\n for _ in 0 ..< 10_000 {\n str = b.testToString()\n }\n check(str != "" && str == "Default string value no tagged pointer")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubFromNSString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubFromNSString()\n }\n }\n#endif\n}\n\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubToNSString() {\n let b = BridgeTester()\n let str = "hello world"\n for _ in 0 ..< 1_000 {\n b.test(from: str)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubToNSString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubToNSString()\n }\n }\n#endif\n}\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubFromArrayOfNSString() {\n let b = BridgeTester()\n var arr : [String] = []\n var str = ""\n for _ in 0 ..< 100 {\n arr = b.testToArrayOfStrings()\n str = arr[0]\n }\n check(str != "" && str == "Default string value no tagged pointer")\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubFromArrayOfNSString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubFromArrayOfNSString()\n }\n }\n#endif\n}\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubToArrayOfNSString() {\n let b = BridgeTester()\n let str = "hello world"\n let arr = [str, str, str, str, str, str, str, str, str, str]\n for _ in 0 ..< 50 {\n b.test(fromArrayOf: arr)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubToArrayOfNSString(_ n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubToArrayOfNSString()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubFromNSDate() {\n let b = BridgeTester()\n\n for _ in 0 ..< 10_000 {\n let bridgedBegin = b.beginDate()\n let bridgedEnd = b.endDate()\n let _ = bridgedEnd.timeIntervalSince(bridgedBegin)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubFromNSDate(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubFromNSDate()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\npublic func testObjectiveCBridgeStubToNSDate() {\n let b = BridgeTester()\n let d = Date()\n for _ in 0 ..< 1_000 {\n b.use(d)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubToNSDate(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubToNSDate()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubDateAccess() {\n var remainders = 0.0\n let d = Date()\n for _ in 0 ..< 100_000 {\n remainders += d.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 10)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubDateAccess(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubDateAccess()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubDateMutation() {\n var d = Date()\n for _ in 0 ..< 100_000 {\n d += 1\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubDateMutation(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubDateMutation()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubURLAppendPath() {\n let startUrl = URL(string: "/")!\n for _ in 0 ..< 10 {\n var url = startUrl\n for _ in 0 ..< 10 {\n url.appendPathComponent("foo")\n }\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubURLAppendPath(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubURLAppendPath()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubDataAppend() {\n let proto = Data()\n var value: UInt8 = 1\n for _ in 0 ..< 50 {\n var d = proto\n for _ in 0 ..< 100 {\n d.append(&value, count: 1)\n }\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubDataAppend(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubDataAppend()\n }\n }\n#endif\n}\n\n@inline(never)\ninternal func getStringsToBridge() -> [String] {\n let strings1 = ["hello", "the quick brown fox jumps over the lazy dog", "the quick brown fox jumps over the lazy dög"]\n return strings1 + strings1.map { $0 + $0 } //mix of literals and non-literals\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringIsEqual(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testIsEqualToString()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringIsEqual2(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testIsEqualToString2()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringIsEqualAllSwift(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testIsEqualToStringAllSwift()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringCompare(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testCompare()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringCompare2(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testCompare2()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringGetASCIIContents(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testGetASCIIContents()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringGetUTF8Contents(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testGetUTF8Contents()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringRangeOfString(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testRangeOfString()\n }\n }\n #endif\n}\n\n@inline(__always)\nfunc run_rangeOfStringSpecific(needle: String, haystack: String, n: Int) {\n#if _runtime(_ObjC)\n b.testRangeOfStringSpecific(withNeedle: needle, haystack: haystack, n: n)\n#endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringRangeOfStringAllSwift(n: Int) {\n run_rangeOfStringSpecific(needle: "y", haystack: "The quick brown fox jumps over the lazy dog", n: 100 * n)\n}\n\nvar longNativeASCII: String! = nil\nvar longNativeNonASCII: String! = nil\npublic func setup_SpecificRangeOfStringBridging() {\n setup_StringBridgeBenchmark()\n longNativeASCII = Array(repeating: "The quick brown fox jump over the lazy dog", count: 1000).joined() + "s"\n longNativeNonASCII = "ü" + longNativeASCII + "ö"\n \n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystack(n: Int) {\n run_rangeOfStringSpecific(needle: "s", haystack: longNativeASCII, n: n)\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystackNonASCII(n: Int) {\n run_rangeOfStringSpecific(needle: "s", haystack: longNativeNonASCII, n: n)\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringRangeOfStringAllSwiftNonASCII(n: Int) {\n run_rangeOfStringSpecific(needle: "ü", haystack: "The quick brown fox jump over the lazy dogü", n: 100 * n)\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringRangeOfStringAllSwiftLongHaystackLongNeedle(n: Int) {\n run_rangeOfStringSpecific(needle: "The quick brown fox jump over the lazy dogs", haystack: longNativeASCII, n: n)\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringHash(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testHash()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringUTF8String(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testUTF8String()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func run_ObjectiveCBridgeStringCStringUsingEncoding(n: Int) {\n #if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n b.testCStringUsingEncoding()\n }\n }\n #endif\n}\n\n@inline(never)\npublic func setup_StringBridgeBenchmark() {\n#if _runtime(_ObjC)\n b = BridgeTester()\n b.setUpStringTests(getStringsToBridge())\n#endif\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ObjectiveCBridgingStubs.swift | cpp_apple_swift_benchmark_single-source_ObjectiveCBridgingStubs.swift | Swift | 13,637 | 0.95 | 0.136095 | 0.170996 | react-lib | 55 | 2024-09-09T23:34:22.567242 | MIT | false | e2f90eb050cace7741344cb414617ca4 |
//===--- ObjectiveCNoBridgingStubs.swift ----------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// This file is compiled with -Xfrontend -disable-swift-bridge-attr. No bridging\n// of swift types happens.\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Foundation\n#if _runtime(_ObjC)\nimport ObjectiveCTests\n#endif\n\nlet t: [BenchmarkCategory] = [.validation, .bridging, .cpubench]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "ObjectiveCBridgeStubToNSStringRef",\n runFunction: run_ObjectiveCBridgeStubToNSStringRef, tags: t),\n BenchmarkInfo(name: "ObjectiveCBridgeStubToNSDateRef",\n runFunction: run_ObjectiveCBridgeStubToNSDateRef, tags: t,\n legacyFactor: 20),\n BenchmarkInfo(name: "ObjectiveCBridgeStubNSDateRefAccess",\n runFunction: run_ObjectiveCBridgeStubNSDateRefAccess, tags: t),\n BenchmarkInfo(name: "ObjectiveCBridgeStubNSDateMutationRef",\n runFunction: run_ObjectiveCBridgeStubNSDateMutationRef, tags: t,\n legacyFactor: 4),\n BenchmarkInfo(name: "ObjectiveCBridgeStubNSDataAppend",\n runFunction: run_ObjectiveCBridgeStubNSDataAppend, tags: t,\n legacyFactor: 10),\n BenchmarkInfo(name: "ObjectiveCBridgeStubFromNSStringRef",\n runFunction: run_ObjectiveCBridgeStubFromNSStringRef, tags: t),\n BenchmarkInfo(name: "ObjectiveCBridgeStubFromNSDateRef",\n runFunction: run_ObjectiveCBridgeStubFromNSDateRef, tags: t,\n legacyFactor: 10),\n BenchmarkInfo(name: "ObjectiveCBridgeStubURLAppendPathRef2",\n runFunction: run_ObjectiveCBridgeStubURLAppendPathRef, tags: t,\n legacyFactor: 10),\n]\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubFromNSStringRef() {\n let b = BridgeTester()\n var nsString : NSString = NSString()\n for _ in 0 ..< 10_000 {\n nsString = b.testToString()\n }\n check(nsString.isEqual(to: "Default string value no tagged pointer" as NSString))\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubFromNSStringRef(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubFromNSStringRef()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubToNSStringRef() {\n let b = BridgeTester()\n let str = NSString(cString: "hello world", encoding: String.Encoding.utf8.rawValue)!\n for _ in 0 ..< 10_000 {\n b.test(from: str)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubToNSStringRef(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubToNSStringRef()\n }\n }\n#endif\n}\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubFromNSDateRef() {\n let b = BridgeTester()\n for _ in 0 ..< 10_000 {\n let bridgedBegin = b.beginDate()\n let bridgedEnd = b.endDate()\n let _ = bridgedEnd.timeIntervalSince(bridgedBegin)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubFromNSDateRef(n: Int) {\n#if _runtime(_ObjC)\n autoreleasepool {\n for _ in 0 ..< n {\n testObjectiveCBridgeStubFromNSDateRef()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\npublic func testObjectiveCBridgeStubToNSDateRef() {\n let b = BridgeTester()\n let d = NSDate()\n for _ in 0 ..< 1_000 {\n b.use(d)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubToNSDateRef(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< 5 * n {\n autoreleasepool {\n testObjectiveCBridgeStubToNSDateRef()\n }\n }\n#endif\n}\n\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubNSDateRefAccess() {\n var remainders = 0.0\n let d = NSDate()\n for _ in 0 ..< 100_000 {\n remainders += d.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 10)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubNSDateRefAccess(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubNSDateRefAccess()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubNSDateMutationRef() {\n var d = NSDate()\n for _ in 0 ..< 25 {\n d = d.addingTimeInterval(1)\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubNSDateMutationRef(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< 100 * n {\n autoreleasepool {\n testObjectiveCBridgeStubNSDateMutationRef()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubURLAppendPathRef() {\n let startUrl = URL(string: "/")!\n for _ in 0 ..< 10 {\n var url = startUrl\n for _ in 0 ..< 10 {\n url = url.appendingPathComponent("foo")\n }\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubURLAppendPathRef(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubURLAppendPathRef()\n }\n }\n#endif\n}\n\n#if _runtime(_ObjC)\n@inline(never)\nfunc testObjectiveCBridgeStubNSDataAppend() {\n let proto = NSMutableData()\n var value: UInt8 = 1\n for _ in 0 ..< 100 {\n let d = proto.mutableCopy() as! NSMutableData\n for _ in 0 ..< 100 {\n d.append(&value, length: 1)\n }\n }\n}\n#endif\n\n@inline(never)\npublic func run_ObjectiveCBridgeStubNSDataAppend(n: Int) {\n#if _runtime(_ObjC)\n for _ in 0 ..< n {\n autoreleasepool {\n testObjectiveCBridgeStubNSDataAppend()\n }\n }\n#endif\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ObjectiveCNoBridgingStubs.swift | cpp_apple_swift_benchmark_single-source_ObjectiveCNoBridgingStubs.swift | Swift | 5,668 | 0.95 | 0.16087 | 0.236967 | awesome-app | 387 | 2024-12-05T11:06:20.501171 | GPL-3.0 | false | b4f44b77ccd25d745be8d0710532f926 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ObserverClosure",\n runFunction: run_ObserverClosure,\n tags: [.validation],\n legacyFactor: 10)\n\nclass Observer {\n @inline(never)\n func receive(_ value: Int) {\n }\n}\n\nclass Signal {\n var observers: [(Int) -> ()] = []\n\n func subscribe(_ observer: @escaping (Int) -> ()) {\n observers.append(observer)\n }\n\n func send(_ value: Int) {\n for observer in observers {\n observer(value)\n }\n }\n}\n\npublic func run_ObserverClosure(_ iterations: Int) {\n let signal = Signal()\n let observer = Observer()\n for _ in 0 ..< 1_000 * iterations {\n signal.subscribe { i in observer.receive(i) }\n }\n signal.send(1)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ObserverClosure.swift | cpp_apple_swift_benchmark_single-source_ObserverClosure.swift | Swift | 1,221 | 0.95 | 0.12 | 0.261905 | awesome-app | 517 | 2024-09-20T17:57:08.721110 | GPL-3.0 | false | 98d92d82bc0233a0817f4dabd80554d7 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ObserverForwarderStruct",\n runFunction: run_ObserverForwarderStruct,\n tags: [.validation],\n legacyFactor: 5)\n\nclass Observer {\n @inline(never)\n func receive(_ value: Int) {\n }\n}\n\nprotocol Sink {\n func receive(_ value: Int)\n}\n\nstruct Forwarder: Sink {\n let object: Observer\n\n func receive(_ value: Int) {\n object.receive(value)\n }\n}\n\nclass Signal {\n var observers: [Sink] = []\n\n func subscribe(_ sink: Sink) {\n observers.append(sink)\n }\n\n func send(_ value: Int) {\n for observer in observers {\n observer.receive(value)\n }\n }\n}\n\npublic func run_ObserverForwarderStruct(_ iterations: Int) {\n let signal = Signal()\n let observer = Observer()\n for _ in 0 ..< 2_000 * iterations {\n signal.subscribe(Forwarder(object: observer))\n }\n signal.send(1)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ObserverForwarderStruct.swift | cpp_apple_swift_benchmark_single-source_ObserverForwarderStruct.swift | Swift | 1,380 | 0.95 | 0.098361 | 0.215686 | vue-tools | 814 | 2024-02-15T02:34:31.591843 | GPL-3.0 | false | 71dd0625daa05882ddb9c394c5233071 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ObserverPartiallyAppliedMethod",\n runFunction: run_ObserverPartiallyAppliedMethod,\n tags: [.validation],\n legacyFactor: 20)\n\nclass Observer {\n @inline(never)\n func receive(_ value: Int) {\n }\n}\n\nclass Signal {\n var observers: [(Int) -> ()] = []\n\n func subscribe(_ observer: @escaping (Int) -> ()) {\n observers.append(observer)\n }\n\n func send(_ value: Int) {\n for observer in observers {\n observer(value)\n }\n }\n}\n\npublic func run_ObserverPartiallyAppliedMethod(_ iterations: Int) {\n let signal = Signal()\n let observer = Observer()\n for _ in 0 ..< 500 * iterations {\n signal.subscribe(observer.receive)\n }\n signal.send(1)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ObserverPartiallyAppliedMethod.swift | cpp_apple_swift_benchmark_single-source_ObserverPartiallyAppliedMethod.swift | Swift | 1,252 | 0.95 | 0.122449 | 0.261905 | python-kit | 158 | 2024-04-27T11:20:31.643396 | Apache-2.0 | false | 96fcaf3bb8db6879323c695060fa7b50 |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "ObserverUnappliedMethod",\n runFunction: run_ObserverUnappliedMethod,\n tags: [.validation],\n legacyFactor: 10)\n\nclass Observer {\n @inline(never)\n func receive(_ value: Int) {\n }\n}\n\nprotocol Sink {\n func receive(_ value: Int)\n}\n\nstruct Forwarder<Object>: Sink {\n let object: Object\n let method: (Object) -> (Int) -> ()\n\n func receive(_ value: Int) {\n method(object)(value)\n }\n}\n\nclass Signal {\n var observers: [Sink] = []\n\n func subscribe(_ sink: Sink) {\n observers.append(sink)\n }\n\n func send(_ value: Int) {\n for observer in observers {\n observer.receive(value)\n }\n }\n}\n\npublic func run_ObserverUnappliedMethod(_ iterations: Int) {\n let signal = Signal()\n let observer = Observer()\n for _ in 0 ..< 1_000 * iterations {\n let forwarder = Forwarder(object: observer, method: Observer.receive)\n signal.subscribe(forwarder)\n }\n signal.send(1)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ObserverUnappliedMethod.swift | cpp_apple_swift_benchmark_single-source_ObserverUnappliedMethod.swift | Swift | 1,481 | 0.95 | 0.095238 | 0.207547 | vue-tools | 763 | 2024-09-27T05:32:27.350426 | GPL-3.0 | false | 05dbbb07a96023b2a09dea1f69461a58 |
//===--- OpaqueConsumingUsers.swift ---------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "OpaqueConsumingUsers",\n runFunction: run_OpaqueConsumingUsers,\n tags: [.regression, .abstraction, .refcount],\n setUpFunction: setup_OpaqueConsumingUsers,\n legacyFactor: 20)\n\n// This test exercises the ability of the optimizer to propagate the +1 from a\n// consuming argument of a non-inlineable through multiple non-inlinable call\n// frames.\n//\n// We are trying to simulate a user application that calls into a resilient\n// setter or initialization. We want to be able to propagate the +1 from the\n// setter through the app as far as we can.\n\nclass Klass {}\n\nclass ConsumingUser {\n var _innerValue: Klass = Klass()\n\n var value: Klass {\n @inline(never) get {\n return _innerValue\n }\n @inline(never) set {\n _innerValue = newValue\n }\n }\n}\n\nvar data: Klass? = nil\nvar user: ConsumingUser? = nil\n\nfunc setup_OpaqueConsumingUsers() {\n switch (data, user) {\n case (let x?, let y?):\n let _ = x\n let _ = y\n return\n case (nil, nil):\n data = Klass()\n user = ConsumingUser()\n default:\n fatalError("Data and user should both be .none or .some")\n }\n}\n\n@inline(never)\nfunc callFrame1(_ data: Klass, _ user: ConsumingUser) {\n callFrame2(data, user)\n}\n\n@inline(never)\nfunc callFrame2(_ data: Klass, _ user: ConsumingUser) {\n callFrame3(data, user)\n}\n\n@inline(never)\nfunc callFrame3(_ data: Klass, _ user: ConsumingUser) {\n callFrame4(data, user)\n}\n\n@inline(never)\nfunc callFrame4(_ data: Klass, _ user: ConsumingUser) {\n user.value = data\n}\n\n@inline(never)\npublic func run_OpaqueConsumingUsers(_ n: Int) {\n let d = data.unsafelyUnwrapped\n let u = user.unsafelyUnwrapped\n for _ in 0..<n*10_000 {\n callFrame4(d, u)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_OpaqueConsumingUsers.swift | cpp_apple_swift_benchmark_single-source_OpaqueConsumingUsers.swift | Swift | 2,262 | 0.95 | 0.066667 | 0.233766 | react-lib | 160 | 2024-02-01T14:38:56.885750 | MIT | false | 4c6e3f7325aa237c3ed8e0d040cb656c |
//===--- OpenClose.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// A micro benchmark for checking the speed of string-based enums.\npublic let benchmarks =\n BenchmarkInfo(\n name: "OpenClose",\n runFunction: run_OpenClose,\n tags: [.validation, .api, .String])\n\nenum MyState : String {\n case Closed = "Closed"\n case Opened = "Opened"\n}\n\n@inline(never)\nfunc check_state(_ state : MyState) -> Int {\n return state == .Opened ? 1 : 0\n}\n\n@inline(never)\npublic func run_OpenClose(_ n: Int) {\n var c = 0\n for _ in 1...n*10000 {\n c += check_state(identity(MyState.Closed))\n }\n check(c == 0)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_OpenClose.swift | cpp_apple_swift_benchmark_single-source_OpenClose.swift | Swift | 1,082 | 0.95 | 0.102564 | 0.352941 | node-utils | 107 | 2024-10-13T16:17:49.969467 | Apache-2.0 | false | 9221205bb26a9b1e74eace983a634a8a |
//===--- Phonebook.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test is based on util/benchmarks/Phonebook, with modifications\n// for performance measuring.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Phonebook",\n runFunction: run_Phonebook,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(names) },\n legacyFactor: 7\n )\n\nlet words = [\n "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph",\n "Charles", "Thomas", "Christopher", "Daniel", "Matthew", "Donald", "Anthony",\n "Paul", "Mark", "George", "Steven", "Kenneth", "Andrew", "Edward", "Brian",\n "Joshua", "Kevin", "Ronald", "Timothy", "Jason", "Jeffrey", "Gary", "Ryan",\n "Nicholas", "Eric", "Stephen", "Jacob", "Larry", "Frank", "Jonathan", "Scott",\n]\nlet names: [Record] = {\n // The list of names in the phonebook.\n var names = [Record]()\n names.reserveCapacity(words.count * words.count)\n for first in words {\n for last in words {\n names.append(Record(first, last))\n }\n }\n return names\n}()\n\n// This is a phone book record.\nstruct Record : Comparable {\n var first: String\n var last: String\n\n init(_ first_ : String,_ last_ : String) {\n first = first_\n last = last_\n }\n}\nfunc ==(lhs: Record, rhs: Record) -> Bool {\n return lhs.last == rhs.last && lhs.first == rhs.first\n}\n\nfunc <(lhs: Record, rhs: Record) -> Bool {\n if lhs.last < rhs.last {\n return true\n }\n if lhs.last > rhs.last {\n return false\n }\n\n if lhs.first < rhs.first {\n return true\n }\n\n return false\n}\n\n@inline(never)\npublic func run_Phonebook(_ n: Int) {\n for _ in 1...n {\n var t = names\n t.sort()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Phonebook.swift | cpp_apple_swift_benchmark_single-source_Phonebook.swift | Swift | 2,121 | 0.95 | 0.1125 | 0.211268 | react-lib | 203 | 2024-10-14T16:05:20.790346 | BSD-3-Clause | false | 32f99dc335f371ab702aeeb2e23a29d3 |
//===--- PointerArithmetics.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "PointerArithmetics",\n runFunction: run_PointerArithmetics,\n tags: [.validation, .api],\n legacyFactor: 100),\n]\n\n@inline(never)\npublic func run_PointerArithmetics(_ n: Int) {\n var numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)\n\n var c = 0\n withUnsafePointer(to: &numbers) {\n $0.withMemoryRebound(to: Int.self, capacity: 10) { ptr in\n for _ in 1...n*100_000 {\n c += (ptr + getInt(10) - getInt(5)).pointee\n }\n }\n }\n check(c != 0)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_PointerArithmetics.swift | cpp_apple_swift_benchmark_single-source_PointerArithmetics.swift | Swift | 1,041 | 0.95 | 0.085714 | 0.354839 | awesome-app | 213 | 2025-03-04T23:50:29.880939 | BSD-3-Clause | false | 7c77d9eb29bc396dcfa74050b77d0e0d |
//===--- PolymorphicCalls.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n/*\nThis benchmark is used to check the performance of polymorphic invocations.\nEssentially, it checks how good a compiler can optimize virtual calls of class\nmethods in cases where multiple sub-classes of a given class are available.\n\nIn particular, this benchmark would benefit from a good devirtualization.\nIn case of applying a speculative devirtualization, it would be benefit from\napplying a jump-threading in combination with the speculative devirtualization.\n*/\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "PolymorphicCalls",\n runFunction: run_PolymorphicCalls,\n tags: [.abstraction, .cpubench]\n ),\n]\n\npublic class A {\n let b: B\n init(b:B) {\n self.b = b\n }\n\n public func run1() -> Int {\n return b.f1() + b.f2() + b.f3()\n }\n\n public func run2() -> Int {\n return b.run()\n }\n}\n\n// B has no known subclasses\npublic class B {\n let x: Int\n init(x:Int) {\n self.x = x\n }\n public func f1() -> Int {\n return x + 1\n }\n public func f2() -> Int {\n return x + 11\n }\n public func f3() -> Int {\n return x + 111\n }\n public func run() -> Int {\n return f1() + f2() + f3()\n }\n}\n\n\npublic class A1 {\n let b: B1\n public init(b:B1) {\n self.b = b\n }\n public func run1() -> Int {\n return b.f1() + b.f2() + b.f3()\n }\n public func run2() -> Int {\n return b.run()\n }\n}\n\n// B1 has 1 known subclass\npublic class B1 {\n func f1() -> Int { return 0 }\n func f2() -> Int { return 0 }\n func f3() -> Int { return 0 }\n public func run() -> Int {\n return f1() + f2() + f3()\n }\n}\n\npublic class C1: B1 {\n let x: Int\n init(x:Int) {\n self.x = x\n }\n override public func f1() -> Int {\n return x + 2\n }\n override public func f2() -> Int {\n return x + 22\n }\n override public func f3() -> Int {\n return x + 222\n }\n}\n\n\npublic class A2 {\n let b:B2\n public init(b:B2) {\n self.b = b\n }\n public func run1() -> Int {\n return b.f1() + b.f2() + b.f3()\n }\n public func run2() -> Int {\n return b.run()\n }\n}\n\n// B2 has 2 known subclasses\npublic class B2 {\n func f1() -> Int { return 0 }\n func f2() -> Int { return 0 }\n func f3() -> Int { return 0 }\n public func run() -> Int {\n return f1() + f2() + f3()\n }\n}\n\npublic class C2 : B2 {\n let x: Int\n init(x:Int) {\n self.x = x\n }\n override public func f1() -> Int {\n return x + 3\n }\n override public func f2() -> Int {\n return x + 33\n }\n override public func f3() -> Int {\n return x + 333\n }\n}\n\npublic class D2 : B2 {\n let x: Int\n init(x:Int) {\n self.x = x\n }\n override public func f1() -> Int {\n return x + 4\n }\n override public func f2() -> Int {\n return x + 44\n }\n override public func f3() -> Int {\n return x + 444\n }\n}\n\n\npublic class A3 {\n let b: B3\n\n public init(b:B3) {\n self.b = b\n }\n\n public func run1() -> Int {\n return b.f1() + b.f2() + b.f3()\n }\n public func run2() -> Int {\n return b.run()\n }\n}\n\n\n// B3 has 3 known subclasses\npublic class B3 {\n func f1() -> Int { return 0 }\n func f2() -> Int { return 0 }\n func f3() -> Int { return 0 }\n public func run() -> Int {\n return f1() + f2() + f3()\n }\n}\n\n\npublic class C3: B3 {\n let x: Int\n init(x:Int) {\n self.x = x\n }\n override public func f1() -> Int {\n return x + 5\n }\n override public func f2() -> Int {\n return x + 55\n }\n override public func f3() -> Int {\n return x + 555\n }\n}\npublic class D3: B3 {\n let x: Int\n init(x:Int) {\n self.x = x\n }\n override public func f1() -> Int {\n return x + 6\n }\n override public func f2() -> Int {\n return x + 66\n }\n override public func f3() -> Int {\n return x + 666\n }\n}\npublic class E3:B3 {\n let x: Int\n init(x:Int) {\n self.x = x\n }\n override public func f1() -> Int {\n return x + 7\n }\n override public func f2() -> Int {\n return x + 77\n }\n override public func f3() -> Int {\n return x + 777\n }\n}\npublic class F3 : B3 {\n let x: Int\n init(x:Int) {\n self.x = x\n }\n override public func f1() -> Int {\n return x + 8\n }\n override public func f2() -> Int {\n return x + 88\n }\n override public func f3() -> Int {\n return x + 888\n }}\n\n// Test the cost of polymorphic method invocation\n// on a class without any subclasses\n@inline(never)\nfunc test(_ a:A, _ upTo: Int) -> Int64 {\n var cnt: Int64 = 0\n for _ in 0..<upTo {\n cnt += Int64(a.run2())\n }\n return cnt\n}\n\n// Test the cost of polymorphic method invocation\n// on a class with 1 subclass\n@inline(never)\nfunc test(_ a:A1, _ upTo: Int) -> Int64 {\n var cnt: Int64 = 0\n for _ in 0..<upTo {\n cnt += Int64(a.run2())\n }\n return cnt\n}\n\n// Test the cost of polymorphic method invocation\n// on a class with 2 subclasses\n@inline(never)\nfunc test(_ a:A2, _ upTo: Int) -> Int64 {\n var cnt: Int64 = 0\n for _ in 0..<upTo {\n cnt += Int64(a.run2())\n }\n return cnt\n}\n\n// Test the cost of polymorphic method invocation\n// on a class with 2 subclasses on objects\n// of different subclasses\n@inline(never)\nfunc test(_ a2_c2:A2, _ a2_d2:A2, _ upTo: Int) -> Int64 {\n var cnt: Int64 = 0\n for _ in 0..<upTo/2 {\n cnt += Int64(a2_c2.run2())\n cnt += Int64(a2_d2.run2())\n }\n return cnt\n}\n\n// Test the cost of polymorphic method invocation\n// on a class with 4 subclasses on objects\n// of different subclasses\n@inline(never)\nfunc test(_ a3_c3: A3, _ a3_d3: A3, _ a3_e3: A3, _ a3_f3: A3, _ upTo: Int) -> Int64 {\n var cnt: Int64 = 0\n for _ in 0..<upTo/4 {\n cnt += Int64(a3_c3.run2())\n cnt += Int64(a3_d3.run2())\n cnt += Int64(a3_e3.run2())\n cnt += Int64(a3_f3.run2())\n }\n return cnt\n}\n\nlet a = A(b:B(x:1))\nlet a1 = A1(b:C1(x:1))\nlet a2 = A2(b:C2(x:1))\nlet a2_c2 = A2(b:C2(x:1))\nlet a2_d2 = A2(b:D2(x:1))\nlet a3_c3 = A3(b:C3(x:1))\nlet a3_d3 = A3(b:D3(x:1))\nlet a3_e3 = A3(b:E3(x:1))\nlet a3_f3 = A3(b:F3(x:1))\n\n@inline(never)\npublic func run_PolymorphicCalls(_ N:Int) {\n let upTo = 10_000 * N\n _ = test(a, upTo)\n _ = test(a1, upTo)\n _ = test(a2, upTo)\n _ = test(a2_c2, a2_d2, upTo)\n _ = test(a3_c3, a3_d3, a3_e3, a3_f3, upTo)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_PolymorphicCalls.swift | cpp_apple_swift_benchmark_single-source_PolymorphicCalls.swift | Swift | 7,015 | 0.95 | 0.087613 | 0.09699 | react-lib | 808 | 2024-05-02T00:09:13.696409 | GPL-3.0 | false | 55f39e0bb0da660375b4750f4cd797dc |
//===--- PopFront.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "PopFrontArray",\n runFunction: run_PopFrontArray,\n tags: [.validation, .api, .Array],\n legacyFactor: 20),\n BenchmarkInfo(name: "PopFrontUnsafePointer",\n runFunction: run_PopFrontUnsafePointer,\n tags: [.validation, .api],\n legacyFactor: 100),\n]\n\nlet arrayCount = 1024\n\n@inline(never)\npublic func run_PopFrontArray(_ n: Int) {\n let orig = Array(repeating: 1, count: arrayCount)\n var a = [Int]()\n for _ in 1...n {\n var result = 0\n a.append(contentsOf: orig)\n while a.count != 0 {\n result += a[0]\n a.remove(at: 0)\n }\n check(result == arrayCount)\n }\n}\n\n@inline(never)\npublic func run_PopFrontUnsafePointer(_ n: Int) {\n let orig = Array(repeating: 1, count: arrayCount)\n let a = UnsafeMutablePointer<Int>.allocate(capacity: arrayCount)\n for _ in 1...n {\n for i in 0..<arrayCount {\n a[i] = orig[i]\n }\n var result = 0\n var count = arrayCount\n while count != 0 {\n result += a[0]\n a.update(from: a + 1, count: count - 1)\n count -= 1\n }\n check(result == arrayCount)\n }\n a.deallocate()\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_PopFront.swift | cpp_apple_swift_benchmark_single-source_PopFront.swift | Swift | 1,693 | 0.95 | 0.114754 | 0.196429 | react-lib | 857 | 2025-04-16T17:01:57.738419 | MIT | false | 8508cccf72d5929a2d26fd8340d7b8ce |
//===--- PopFrontGeneric.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "PopFrontArrayGeneric",\n runFunction: run_PopFrontArrayGeneric,\n tags: [.validation, .api, .Array],\n legacyFactor: 20)\n\nlet arrayCount = 1024\n\n// This test case exposes rdar://17440222 which caused rdar://17974483 (popFront\n// being really slow).\nprotocol MyArrayBufferProtocol : MutableCollection, RandomAccessCollection {\n mutating func myReplace<C>(\n _ subRange: Range<Int>,\n with newValues: C\n ) where C : Collection, C.Element == Element\n}\n\nextension Array : MyArrayBufferProtocol {\n mutating func myReplace<C>(\n _ subRange: Range<Int>,\n with newValues: C\n ) where C : Collection, C.Element == Element {\n replaceSubrange(subRange, with: newValues)\n }\n}\n\nfunc myArrayReplace<\n B: MyArrayBufferProtocol,\n C: Collection\n>(_ target: inout B, _ subRange: Range<Int>, _ newValues: C)\n where C.Element == B.Element, B.Index == Int {\n target.myReplace(subRange, with: newValues)\n}\n\n@inline(never)\npublic func run_PopFrontArrayGeneric(_ n: Int) {\n let orig = Array(repeating: 1, count: arrayCount)\n var a = [Int]()\n for _ in 1...n {\n var result = 0\n a.append(contentsOf: orig)\n while a.count != 0 {\n result += a[0]\n myArrayReplace(&a, 0..<1, EmptyCollection())\n }\n check(result == arrayCount)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_PopFrontGeneric.swift | cpp_apple_swift_benchmark_single-source_PopFrontGeneric.swift | Swift | 1,860 | 0.95 | 0.063492 | 0.232143 | vue-tools | 402 | 2023-07-22T19:53:40.300643 | Apache-2.0 | false | f7ebbaac0c879e2a43bd9a44cfe1fc3a |
//===--- Prefix.swift -----------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to Prefix.swift.gyb and run\n// scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\nimport TestsUtils\n\nlet sequenceCount = 4096\nlet prefixCount = sequenceCount - 1024\nlet sumCount = prefixCount * (prefixCount - 1) / 2\nlet array: [Int] = Array(0..<sequenceCount)\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "PrefixCountableRange",\n runFunction: run_PrefixCountableRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixSequence",\n runFunction: run_PrefixSequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixAnySequence",\n runFunction: run_PrefixAnySequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixAnySeqCntRange",\n runFunction: run_PrefixAnySeqCntRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixAnySeqCRangeIter",\n runFunction: run_PrefixAnySeqCRangeIter,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixAnyCollection",\n runFunction: run_PrefixAnyCollection,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixArray",\n runFunction: run_PrefixArray,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n BenchmarkInfo(\n name: "PrefixCountableRangeLazy",\n runFunction: run_PrefixCountableRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixSequenceLazy",\n runFunction: run_PrefixSequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixAnySequenceLazy",\n runFunction: run_PrefixAnySequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixAnySeqCntRangeLazy",\n runFunction: run_PrefixAnySeqCntRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixAnySeqCRangeIterLazy",\n runFunction: run_PrefixAnySeqCRangeIterLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixAnyCollectionLazy",\n runFunction: run_PrefixAnyCollectionLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixArrayLazy",\n runFunction: run_PrefixArrayLazy,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n]\n\n@inline(never)\npublic func run_PrefixCountableRange(_ n: Int) {\n let s = 0..<sequenceCount\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixSequence(_ n: Int) {\n let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixAnySequence(_ n: Int) {\n let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixAnySeqCntRange(_ n: Int) {\n let s = AnySequence(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixAnySeqCRangeIter(_ n: Int) {\n let s = AnySequence((0..<sequenceCount).makeIterator())\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixAnyCollection(_ n: Int) {\n let s = AnyCollection(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixArray(_ n: Int) {\n let s = array\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixCountableRangeLazy(_ n: Int) {\n let s = (0..<sequenceCount).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixSequenceLazy(_ n: Int) {\n let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixAnySequenceLazy(_ n: Int) {\n let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixAnySeqCntRangeLazy(_ n: Int) {\n let s = (AnySequence(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixAnySeqCRangeIterLazy(_ n: Int) {\n let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixAnyCollectionLazy(_ n: Int) {\n let s = (AnyCollection(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixArrayLazy(_ n: Int) {\n let s = (array).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(prefixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Prefix.swift | cpp_apple_swift_benchmark_single-source_Prefix.swift | Swift | 6,749 | 0.95 | 0.122951 | 0.079832 | node-utils | 840 | 2024-08-28T14:26:59.311838 | BSD-3-Clause | false | 76d7580d820cbe92bc4687cdc4cb6467 |
//===--- PrefixWhile.swift ------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to PrefixWhile.swift.gyb and run\n// scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\nimport TestsUtils\n\nlet sequenceCount = 4096\nlet prefixCount = sequenceCount - 1024\nlet sumCount = prefixCount * (prefixCount - 1) / 2\nlet array: [Int] = Array(0..<sequenceCount)\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "PrefixWhileCountableRange",\n runFunction: run_PrefixWhileCountableRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileSequence",\n runFunction: run_PrefixWhileSequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileAnySequence",\n runFunction: run_PrefixWhileAnySequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileAnySeqCntRange",\n runFunction: run_PrefixWhileAnySeqCntRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileAnySeqCRangeIter",\n runFunction: run_PrefixWhileAnySeqCRangeIter,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileAnyCollection",\n runFunction: run_PrefixWhileAnyCollection,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileArray",\n runFunction: run_PrefixWhileArray,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n BenchmarkInfo(\n name: "PrefixWhileCountableRangeLazy",\n runFunction: run_PrefixWhileCountableRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileSequenceLazy",\n runFunction: run_PrefixWhileSequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileAnySequenceLazy",\n runFunction: run_PrefixWhileAnySequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileAnySeqCntRangeLazy",\n runFunction: run_PrefixWhileAnySeqCntRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileAnySeqCRangeIterLazy",\n runFunction: run_PrefixWhileAnySeqCRangeIterLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileAnyCollectionLazy",\n runFunction: run_PrefixWhileAnyCollectionLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "PrefixWhileArrayLazy",\n runFunction: run_PrefixWhileArrayLazy,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n]\n\n@inline(never)\npublic func run_PrefixWhileCountableRange(_ n: Int) {\n let s = 0..<sequenceCount\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileSequence(_ n: Int) {\n let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileAnySequence(_ n: Int) {\n let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileAnySeqCntRange(_ n: Int) {\n let s = AnySequence(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileAnySeqCRangeIter(_ n: Int) {\n let s = AnySequence((0..<sequenceCount).makeIterator())\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileAnyCollection(_ n: Int) {\n let s = AnyCollection(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileArray(_ n: Int) {\n let s = array\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileCountableRangeLazy(_ n: Int) {\n let s = (0..<sequenceCount).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileSequenceLazy(_ n: Int) {\n let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileAnySequenceLazy(_ n: Int) {\n let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileAnySeqCntRangeLazy(_ n: Int) {\n let s = (AnySequence(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileAnySeqCRangeIterLazy(_ n: Int) {\n let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileAnyCollectionLazy(_ n: Int) {\n let s = (AnyCollection(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_PrefixWhileArrayLazy(_ n: Int) {\n let s = (array).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.prefix(while: {$0 < prefixCount} ) {\n result += element\n }\n check(result == sumCount)\n }\n}\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_PrefixWhile.swift | cpp_apple_swift_benchmark_single-source_PrefixWhile.swift | Swift | 7,174 | 0.95 | 0.180328 | 0.079832 | react-lib | 280 | 2024-12-09T18:46:01.635413 | MIT | false | d6f80930221d5ffa8add2576941d776c |
//===--- Prims.swift ------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// The test implements Prim's algorithm for minimum spanning tree building.\n// http://en.wikipedia.org/wiki/Prim%27s_algorithm\n\n// This class implements array-based heap (priority queue).\n// It is used to store edges from nodes in spanning tree to nodes outside of it.\n// We are interested only in the edges with the smallest costs, so if there are\n// several edges pointing to the same node, we keep only one from them. Thus,\n// it is enough to record this node instead.\n// We maintain a map (node index in graph)->(node index in heap) to be able to\n// update the heap fast when we add a new node to the tree.\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "Prims",\n runFunction: run_Prims,\n tags: [.validation, .algorithm],\n legacyFactor: 5),\n]\n\nclass PriorityQueue {\n final var heap: Array<EdgeCost>\n final var graphIndexToHeapIndexMap: Array<Int?>\n\n // Create heap for graph with NUM nodes.\n init(Num: Int) {\n heap = Array<EdgeCost>()\n graphIndexToHeapIndexMap = Array<Int?>(repeating:nil, count: Num)\n }\n\n func isEmpty() -> Bool {\n return heap.isEmpty\n }\n\n // Insert element N to heap, maintaining the heap property.\n func insert(_ n: EdgeCost) {\n let ind: Int = heap.count\n heap.append(n)\n graphIndexToHeapIndexMap[n.to] = heap.count - 1\n bubbleUp(ind)\n }\n\n // Insert element N if in's not in the heap, or update its cost if the new\n // value is less than the existing one.\n func insertOrUpdate(_ n: EdgeCost) {\n let id = n.to\n let c = n.cost\n if let ind = graphIndexToHeapIndexMap[id] {\n if heap[ind].cost <= c {\n // We don't need an edge with a bigger cost\n return\n }\n heap[ind].cost = c\n heap[ind].from = n.from\n bubbleUp(ind)\n } else {\n insert(n)\n }\n }\n\n // Restore heap property by moving element at index IND up.\n // This is needed after insertion, and after decreasing an element's cost.\n func bubbleUp(_ ind: Int) {\n var ind = ind\n let c = heap[ind].cost\n while (ind != 0) {\n let p = getParentIndex(ind)\n if heap[p].cost > c {\n swap(p, with: ind)\n ind = p\n } else {\n break\n }\n }\n }\n\n // Pop minimum element from heap and restore the heap property after that.\n func pop() -> EdgeCost? {\n if (heap.isEmpty) {\n return nil\n }\n swap(0, with:heap.count-1)\n let r = heap.removeLast()\n graphIndexToHeapIndexMap[r.to] = nil\n bubbleDown(0)\n return r\n }\n\n // Restore heap property by moving element at index IND down.\n // This is needed after removing an element, and after increasing an\n // element's cost.\n func bubbleDown(_ ind: Int) {\n var ind = ind\n let n = heap.count\n while (ind < n) {\n let l = getLeftChildIndex(ind)\n let r = getRightChildIndex(ind)\n if (l >= n) {\n break\n }\n var min: Int\n if (r < n && heap[r].cost < heap[l].cost) {\n min = r\n } else {\n min = l\n }\n if (heap[ind].cost <= heap[min].cost) {\n break\n }\n swap(ind, with: min)\n ind = min\n }\n }\n\n // Swaps elements I and J in the heap and correspondingly updates\n // graphIndexToHeapIndexMap.\n func swap(_ i: Int, with j : Int) {\n if (i == j) {\n return\n }\n (heap[i], heap[j]) = (heap[j], heap[i])\n let (i2, j2) = (heap[i].to, heap[j].to)\n (graphIndexToHeapIndexMap[i2], graphIndexToHeapIndexMap[j2]) =\n (graphIndexToHeapIndexMap[j2], graphIndexToHeapIndexMap[i2])\n }\n\n // Dumps the heap.\n func dump() {\n print("QUEUE")\n for nodeCost in heap {\n let to: Int = nodeCost.to\n let from: Int = nodeCost.from\n let cost: Double = nodeCost.cost\n print("(\(from)->\(to), \(cost))")\n }\n }\n\n func getLeftChildIndex(_ index : Int) -> Int {\n return index*2 + 1\n }\n func getRightChildIndex(_ index : Int) -> Int {\n return (index + 1)*2\n }\n func getParentIndex(_ childIndex : Int) -> Int {\n return (childIndex - 1)/2\n }\n}\n\nstruct GraphNode {\n var id: Int\n var adjList: Array<Int>\n\n init(i : Int) {\n id = i\n adjList = Array<Int>()\n }\n}\n\nstruct EdgeCost {\n var to: Int\n var cost: Double\n var from: Int\n}\n\nstruct Edge : Equatable {\n var start: Int\n var end: Int\n}\n\nfunc ==(lhs: Edge, rhs: Edge) -> Bool {\n return lhs.start == rhs.start && lhs.end == rhs.end\n}\n\nextension Edge : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(start)\n hasher.combine(end)\n }\n}\n\nfunc prims(_ graph : Array<GraphNode>, _ fun : (Int, Int) -> Double) -> Array<Int?> {\n var treeEdges = Array<Int?>(repeating:nil, count:graph.count)\n\n let queue = PriorityQueue(Num:graph.count)\n // Make the minimum spanning tree root its own parent for simplicity.\n queue.insert(EdgeCost(to: 0, cost: 0.0, from: 0))\n\n // Take an element with the smallest cost from the queue and add its\n // neighbors to the queue if their cost was updated\n while !queue.isEmpty() {\n // Add an edge with minimum cost to the spanning tree\n let e = queue.pop()!\n let newnode = e.to\n // Add record about the edge newnode->e.from to treeEdges\n treeEdges[newnode] = e.from\n\n // Check all adjacent nodes and add edges, ending outside the tree, to the\n // queue. If the queue already contains an edge to an adjacent node, we\n // replace existing one with the new one in case the new one costs less.\n for adjNodeIndex in graph[newnode].adjList {\n if treeEdges[adjNodeIndex] != nil {\n continue\n }\n let newcost = fun(newnode, graph[adjNodeIndex].id)\n queue.insertOrUpdate(EdgeCost(to: adjNodeIndex, cost: newcost, from: newnode))\n }\n }\n return treeEdges\n}\n\n@inline(never)\npublic func run_Prims(_ n: Int) {\n for _ in 1...n {\n let nodes : [Int] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,\n 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,\n 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,\n 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,\n 93, 94, 95, 96, 97, 98, 99 ]\n\n // Prim's algorithm is designed for undirected graphs.\n // Due to that, in our set all the edges are paired, i.e. for any\n // edge (start, end, C) there is also an edge (end, start, C).\n let edges : [(Int, Int, Double)] = [\n (26, 47, 921),\n (20, 25, 971),\n (92, 59, 250),\n (33, 55, 1391),\n (78, 39, 313),\n (7, 25, 637),\n (18, 19, 1817),\n (33, 41, 993),\n (64, 41, 926),\n (88, 86, 574),\n (93, 15, 1462),\n (86, 33, 1649),\n (37, 35, 841),\n (98, 51, 1160),\n (15, 30, 1125),\n (65, 78, 1052),\n (58, 12, 1273),\n (12, 17, 285),\n (45, 61, 1608),\n (75, 53, 545),\n (99, 48, 410),\n (97, 0, 1303),\n (48, 17, 1807),\n (1, 54, 1491),\n (15, 34, 807),\n (94, 98, 646),\n (12, 69, 136),\n (65, 11, 983),\n (63, 83, 1604),\n (78, 89, 1828),\n (61, 63, 845),\n (18, 36, 1626),\n (68, 52, 1324),\n (14, 50, 690),\n (3, 11, 943),\n (21, 68, 914),\n (19, 44, 1762),\n (85, 80, 270),\n (59, 92, 250),\n (86, 84, 1431),\n (19, 18, 1817),\n (52, 68, 1324),\n (16, 29, 1108),\n (36, 80, 395),\n (67, 18, 803),\n (63, 88, 1717),\n (68, 21, 914),\n (75, 82, 306),\n (49, 82, 1292),\n (73, 45, 1876),\n (89, 82, 409),\n (45, 47, 272),\n (22, 83, 597),\n (61, 12, 1791),\n (44, 68, 1229),\n (50, 51, 917),\n (14, 53, 355),\n (77, 41, 138),\n (54, 21, 1870),\n (93, 70, 1582),\n (76, 2, 1658),\n (83, 73, 1162),\n (6, 1, 482),\n (11, 65, 983),\n (81, 90, 1024),\n (19, 1, 970),\n (8, 58, 1131),\n (60, 42, 477),\n (86, 29, 258),\n (69, 59, 903),\n (34, 15, 807),\n (37, 2, 1451),\n (7, 73, 754),\n (47, 86, 184),\n (67, 17, 449),\n (18, 67, 803),\n (25, 4, 595),\n (3, 31, 1337),\n (64, 31, 1928),\n (9, 43, 237),\n (83, 63, 1604),\n (47, 45, 272),\n (86, 88, 574),\n (87, 74, 934),\n (98, 94, 646),\n (20, 1, 642),\n (26, 92, 1344),\n (18, 17, 565),\n (47, 11, 595),\n (10, 59, 1558),\n (2, 76, 1658),\n (77, 74, 1277),\n (42, 60, 477),\n (80, 36, 395),\n (35, 23, 589),\n (50, 37, 203),\n (6, 96, 481),\n (78, 65, 1052),\n (1, 52, 127),\n (65, 23, 1932),\n (46, 51, 213),\n (59, 89, 89),\n (15, 93, 1462),\n (69, 3, 1305),\n (17, 37, 1177),\n (30, 3, 193),\n (9, 15, 818),\n (75, 95, 977),\n (86, 47, 184),\n (10, 12, 1736),\n (80, 27, 1010),\n (12, 10, 1736),\n (86, 1, 1958),\n (60, 12, 1240),\n (43, 71, 683),\n (91, 65, 1519),\n (33, 86, 1649),\n (62, 26, 1773),\n (1, 13, 1187),\n (2, 10, 1018),\n (91, 29, 351),\n (69, 12, 136),\n (43, 9, 237),\n (29, 86, 258),\n (17, 48, 1807),\n (31, 64, 1928),\n (68, 61, 1936),\n (76, 38, 1724),\n (1, 6, 482),\n (53, 14, 355),\n (51, 50, 917),\n (54, 13, 815),\n (19, 29, 883),\n (35, 87, 974),\n (70, 96, 511),\n (23, 35, 589),\n (39, 69, 1588),\n (93, 73, 1093),\n (13, 73, 435),\n (5, 60, 1619),\n (42, 41, 1523),\n (66, 58, 1596),\n (1, 67, 431),\n (17, 67, 449),\n (30, 95, 906),\n (71, 43, 683),\n (5, 87, 190),\n (12, 78, 891),\n (30, 97, 402),\n (28, 17, 1131),\n (7, 97, 1356),\n (58, 66, 1596),\n (20, 37, 1294),\n (73, 76, 514),\n (54, 8, 613),\n (68, 35, 1252),\n (92, 32, 701),\n (3, 90, 652),\n (99, 46, 1576),\n (13, 54, 815),\n (20, 87, 1390),\n (36, 18, 1626),\n (51, 26, 1146),\n (2, 23, 581),\n (29, 7, 1558),\n (88, 59, 173),\n (17, 1, 1071),\n (37, 49, 1011),\n (18, 6, 696),\n (88, 33, 225),\n (58, 38, 802),\n (87, 50, 1744),\n (29, 91, 351),\n (6, 71, 1053),\n (45, 24, 1720),\n (65, 91, 1519),\n (37, 50, 203),\n (11, 3, 943),\n (72, 65, 1330),\n (45, 50, 339),\n (25, 20, 971),\n (15, 9, 818),\n (14, 54, 1353),\n (69, 95, 393),\n (8, 66, 1213),\n (52, 2, 1608),\n (50, 14, 690),\n (50, 45, 339),\n (1, 37, 1273),\n (45, 93, 1650),\n (39, 78, 313),\n (1, 86, 1958),\n (17, 28, 1131),\n (35, 33, 1667),\n (23, 2, 581),\n (51, 66, 245),\n (17, 54, 924),\n (41, 49, 1629),\n (60, 5, 1619),\n (56, 93, 1110),\n (96, 13, 461),\n (25, 7, 637),\n (11, 69, 370),\n (90, 3, 652),\n (39, 71, 1485),\n (65, 51, 1529),\n (20, 6, 1414),\n (80, 85, 270),\n (73, 83, 1162),\n (0, 97, 1303),\n (13, 33, 826),\n (29, 71, 1788),\n (33, 12, 461),\n (12, 58, 1273),\n (69, 39, 1588),\n (67, 75, 1504),\n (87, 20, 1390),\n (88, 97, 526),\n (33, 88, 225),\n (95, 69, 393),\n (2, 52, 1608),\n (5, 25, 719),\n (34, 78, 510),\n (53, 99, 1074),\n (33, 35, 1667),\n (57, 30, 361),\n (87, 58, 1574),\n (13, 90, 1030),\n (79, 74, 91),\n (4, 86, 1107),\n (64, 94, 1609),\n (11, 12, 167),\n (30, 45, 272),\n (47, 91, 561),\n (37, 17, 1177),\n (77, 49, 883),\n (88, 23, 1747),\n (70, 80, 995),\n (62, 77, 907),\n (18, 4, 371),\n (73, 93, 1093),\n (11, 47, 595),\n (44, 23, 1990),\n (20, 0, 512),\n (3, 69, 1305),\n (82, 3, 1815),\n (20, 88, 368),\n (44, 45, 364),\n (26, 51, 1146),\n (7, 65, 349),\n (71, 39, 1485),\n (56, 88, 1954),\n (94, 69, 1397),\n (12, 28, 544),\n (95, 75, 977),\n (32, 90, 789),\n (53, 1, 772),\n (54, 14, 1353),\n (49, 77, 883),\n (92, 26, 1344),\n (17, 18, 565),\n (97, 88, 526),\n (48, 80, 1203),\n (90, 32, 789),\n (71, 6, 1053),\n (87, 35, 974),\n (55, 90, 1808),\n (12, 61, 1791),\n (1, 96, 328),\n (63, 10, 1681),\n (76, 34, 871),\n (41, 64, 926),\n (42, 97, 482),\n (25, 5, 719),\n (23, 65, 1932),\n (54, 1, 1491),\n (28, 12, 544),\n (89, 10, 108),\n (27, 33, 143),\n (67, 1, 431),\n (32, 45, 52),\n (79, 33, 1871),\n (6, 55, 717),\n (10, 58, 459),\n (67, 39, 393),\n (10, 4, 1808),\n (96, 6, 481),\n (1, 19, 970),\n (97, 7, 1356),\n (29, 16, 1108),\n (1, 53, 772),\n (30, 15, 1125),\n (4, 6, 634),\n (6, 20, 1414),\n (88, 56, 1954),\n (87, 64, 1950),\n (34, 76, 871),\n (17, 12, 285),\n (55, 59, 321),\n (61, 68, 1936),\n (50, 87, 1744),\n (84, 44, 952),\n (41, 33, 993),\n (59, 18, 1352),\n (33, 27, 143),\n (38, 32, 1210),\n (55, 70, 1264),\n (38, 58, 802),\n (1, 20, 642),\n (73, 13, 435),\n (80, 48, 1203),\n (94, 64, 1609),\n (38, 28, 414),\n (73, 23, 1113),\n (78, 12, 891),\n (26, 62, 1773),\n (87, 43, 579),\n (53, 6, 95),\n (59, 95, 285),\n (88, 63, 1717),\n (17, 5, 633),\n (66, 8, 1213),\n (41, 42, 1523),\n (83, 22, 597),\n (95, 30, 906),\n (51, 65, 1529),\n (17, 49, 1727),\n (64, 87, 1950),\n (86, 4, 1107),\n (37, 98, 1102),\n (32, 92, 701),\n (60, 94, 198),\n (73, 98, 1749),\n (4, 18, 371),\n (96, 70, 511),\n (7, 29, 1558),\n (35, 37, 841),\n (27, 64, 384),\n (12, 33, 461),\n (36, 38, 529),\n (69, 16, 1183),\n (91, 47, 561),\n (85, 29, 1676),\n (3, 82, 1815),\n (69, 58, 1579),\n (93, 45, 1650),\n (97, 42, 482),\n (37, 1, 1273),\n (61, 4, 543),\n (96, 1, 328),\n (26, 0, 1993),\n (70, 64, 878),\n (3, 30, 193),\n (58, 69, 1579),\n (4, 25, 595),\n (31, 3, 1337),\n (55, 6, 717),\n (39, 67, 393),\n (78, 34, 510),\n (75, 67, 1504),\n (6, 53, 95),\n (51, 79, 175),\n (28, 91, 1040),\n (89, 78, 1828),\n (74, 93, 1587),\n (45, 32, 52),\n (10, 2, 1018),\n (49, 37, 1011),\n (63, 61, 845),\n (0, 20, 512),\n (1, 17, 1071),\n (99, 53, 1074),\n (37, 20, 1294),\n (10, 89, 108),\n (33, 92, 946),\n (23, 73, 1113),\n (23, 88, 1747),\n (49, 17, 1727),\n (88, 20, 368),\n (21, 54, 1870),\n (70, 93, 1582),\n (59, 88, 173),\n (32, 38, 1210),\n (89, 59, 89),\n (23, 44, 1990),\n (38, 76, 1724),\n (30, 57, 361),\n (94, 60, 198),\n (59, 10, 1558),\n (55, 64, 1996),\n (12, 11, 167),\n (36, 24, 1801),\n (97, 30, 402),\n (52, 1, 127),\n (58, 87, 1574),\n (54, 17, 924),\n (93, 74, 1587),\n (24, 36, 1801),\n (2, 37, 1451),\n (91, 28, 1040),\n (59, 55, 321),\n (69, 11, 370),\n (8, 54, 613),\n (29, 85, 1676),\n (44, 19, 1762),\n (74, 79, 91),\n (93, 56, 1110),\n (58, 10, 459),\n (41, 50, 1559),\n (66, 51, 245),\n (80, 19, 1838),\n (33, 79, 1871),\n (76, 73, 514),\n (98, 37, 1102),\n (45, 44, 364),\n (16, 69, 1183),\n (49, 41, 1629),\n (19, 80, 1838),\n (71, 57, 500),\n (6, 4, 634),\n (64, 27, 384),\n (84, 86, 1431),\n (5, 17, 633),\n (96, 88, 334),\n (87, 5, 190),\n (70, 21, 1619),\n (55, 33, 1391),\n (10, 63, 1681),\n (11, 62, 1339),\n (33, 13, 826),\n (64, 70, 878),\n (65, 72, 1330),\n (70, 55, 1264),\n (64, 55, 1996),\n (50, 41, 1559),\n (46, 99, 1576),\n (88, 96, 334),\n (51, 20, 868),\n (73, 7, 754),\n (80, 70, 995),\n (44, 84, 952),\n (29, 19, 883),\n (59, 69, 903),\n (57, 53, 1575),\n (90, 13, 1030),\n (28, 38, 414),\n (12, 60, 1240),\n (85, 58, 573),\n (90, 55, 1808),\n (4, 10, 1808),\n (68, 44, 1229),\n (92, 33, 946),\n (90, 81, 1024),\n (53, 75, 545),\n (45, 30, 272),\n (41, 77, 138),\n (21, 70, 1619),\n (45, 73, 1876),\n (35, 68, 1252),\n (13, 96, 461),\n (53, 57, 1575),\n (82, 89, 409),\n (28, 61, 449),\n (58, 61, 78),\n (27, 80, 1010),\n (61, 58, 78),\n (38, 36, 529),\n (80, 30, 397),\n (18, 59, 1352),\n (62, 11, 1339),\n (95, 59, 285),\n (51, 98, 1160),\n (6, 18, 696),\n (30, 80, 397),\n (69, 94, 1397),\n (58, 85, 573),\n (48, 99, 410),\n (51, 46, 213),\n (57, 71, 500),\n (91, 30, 104),\n (65, 7, 349),\n (79, 51, 175),\n (47, 26, 921),\n (4, 61, 543),\n (98, 73, 1749),\n (74, 77, 1277),\n (61, 28, 449),\n (58, 8, 1131),\n (61, 45, 1608),\n (74, 87, 934),\n (71, 29, 1788),\n (30, 91, 104),\n (13, 1, 1187),\n (0, 26, 1993),\n (82, 49, 1292),\n (43, 87, 579),\n (24, 45, 1720),\n (20, 51, 868),\n (77, 62, 907),\n (82, 75, 306),\n ]\n\n // Prepare graph and edge->cost map\n var graph = Array<GraphNode>()\n for n in nodes {\n graph.append(GraphNode(i: n))\n }\n var map = Dictionary<Edge, Double>()\n for tup in edges {\n map[Edge(start: tup.0, end: tup.1)] = tup.2\n graph[tup.0].adjList.append(tup.1)\n }\n\n // Find spanning tree\n let treeEdges = prims(graph, { (start: Int, end: Int) in\n return map[Edge(start: start, end: end)]!\n })\n\n // Compute its cost in order to check results\n var cost = 0.0\n for i in 1..<treeEdges.count {\n if let n = treeEdges[i] { cost += map[Edge(start: n, end: i)]! }\n }\n check(Int(cost) == 49324)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Prims.swift | cpp_apple_swift_benchmark_single-source_Prims.swift | Swift | 18,208 | 0.95 | 0.04194 | 0.065395 | awesome-app | 102 | 2023-11-04T07:22:00.322810 | GPL-3.0 | false | 101c59d9c139619e9765a496ebe91bd9 |
//===--- PrimsNonStrongRefAdjacencyList.swift -----------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n///\n/// \file\n///\n/// The test implements Prim's algorithm for minimum spanning tree building.\n/// http://en.wikipedia.org/wiki/Prim%27s_algorithm\n///\n/// This class implements array-based heap (priority queue). It is used to store\n/// edges from nodes in spanning tree to nodes outside of it. We are interested\n/// only in the edges with the smallest costs, so if there are several edges\n/// pointing to the same node, we keep only one from them. Thus, it is enough to\n/// record this node instead. We maintain a map (node index in graph)->(node\n/// index in heap) to be able to update the heap fast when we add a new node to\n/// the tree.\n///\n/// NOTE: This benchmark purposely internally uses non strong references for its\n/// adjacency list instead of integers to test that code path for the various\n/// types of weak pointers that we use.\n///\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks: [BenchmarkInfo] = ({\n var benchmarks: [BenchmarkInfo] = []\n#if false\n // TODO: Stabilize weak benchmark.\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.Weak",\n runFunction: run_PrimsWeak,\n tags: [.validation, .algorithm],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(weakPrimsState)\n }))\n // TODO: Stabilize weak benchmark.\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.Weak.Closure",\n runFunction: run_PrimsWeakClosureAccess,\n tags: [.validation, .algorithm],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(weakPrimsState)\n }))\n#endif\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.UnownedSafe",\n runFunction: run_PrimsUnownedSafe,\n tags: [.validation, .algorithm],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(unownedSafePrimsState)\n }))\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.UnownedSafe.Closure",\n runFunction: run_PrimsUnownedSafeClosureAccess,\n tags: [.validation, .algorithm],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(unownedSafePrimsState)\n }))\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.UnownedUnsafe",\n runFunction: run_PrimsUnownedUnsafe,\n tags: [.validation, .algorithm],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(unownedUnsafePrimsState)\n }))\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.UnownedUnsafe.Closure",\n runFunction: run_PrimsUnownedUnsafeClosureAccess,\n tags: [.validation, .algorithm],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(unownedUnsafePrimsState)\n }))\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.Unmanaged",\n runFunction: run_PrimsUnmanaged,\n tags: [.validation, .algorithm, .api],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(unmanagedPrimsState)\n }))\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.Unmanaged.Closure",\n runFunction: run_PrimsUnmanagedClosureAccess,\n tags: [.validation, .algorithm, .api],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(unmanagedPrimsState)\n }))\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.UnmanagedUGR",\n runFunction: run_PrimsUnmanagedUGR,\n tags: [.validation, .algorithm, .api],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(unmanagedUGRPrimsState)\n }))\n benchmarks.append(BenchmarkInfo(\n name: "Prims.NonStrongRef.UnmanagedUGR.Closure",\n runFunction: run_PrimsUnmanagedUGRClosureAccess,\n tags: [.validation, .algorithm, .api],\n setUpFunction: {\n touchGlobalInfo()\n blackHole(unmanagedUGRPrimsState)\n }))\n return benchmarks\n })()\n\n//===----------------------------------------------------------------------===//\n// Globals\n//===----------------------------------------------------------------------===//\n\nprivate func touchGlobalInfo() {\n blackHole(nodes)\n blackHole(edges)\n}\n\nlet nodes : [Int] = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,\n 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,\n 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,\n 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60,\n 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,\n 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,\n 93, 94, 95, 96, 97, 98, 99 ]\n\n// Prim's algorithm is designed for undirected graphs.\n// Due to that, in our set all the edges are paired, i.e. for any\n// edge (start, end, C) there is also an edge (end, start, C).\nlet edges : [(Int, Int, Double)] = [\n (26, 47, 921),\n (20, 25, 971),\n (92, 59, 250),\n (33, 55, 1391),\n (78, 39, 313),\n (7, 25, 637),\n (18, 19, 1817),\n (33, 41, 993),\n (64, 41, 926),\n (88, 86, 574),\n (93, 15, 1462),\n (86, 33, 1649),\n (37, 35, 841),\n (98, 51, 1160),\n (15, 30, 1125),\n (65, 78, 1052),\n (58, 12, 1273),\n (12, 17, 285),\n (45, 61, 1608),\n (75, 53, 545),\n (99, 48, 410),\n (97, 0, 1303),\n (48, 17, 1807),\n (1, 54, 1491),\n (15, 34, 807),\n (94, 98, 646),\n (12, 69, 136),\n (65, 11, 983),\n (63, 83, 1604),\n (78, 89, 1828),\n (61, 63, 845),\n (18, 36, 1626),\n (68, 52, 1324),\n (14, 50, 690),\n (3, 11, 943),\n (21, 68, 914),\n (19, 44, 1762),\n (85, 80, 270),\n (59, 92, 250),\n (86, 84, 1431),\n (19, 18, 1817),\n (52, 68, 1324),\n (16, 29, 1108),\n (36, 80, 395),\n (67, 18, 803),\n (63, 88, 1717),\n (68, 21, 914),\n (75, 82, 306),\n (49, 82, 1292),\n (73, 45, 1876),\n (89, 82, 409),\n (45, 47, 272),\n (22, 83, 597),\n (61, 12, 1791),\n (44, 68, 1229),\n (50, 51, 917),\n (14, 53, 355),\n (77, 41, 138),\n (54, 21, 1870),\n (93, 70, 1582),\n (76, 2, 1658),\n (83, 73, 1162),\n (6, 1, 482),\n (11, 65, 983),\n (81, 90, 1024),\n (19, 1, 970),\n (8, 58, 1131),\n (60, 42, 477),\n (86, 29, 258),\n (69, 59, 903),\n (34, 15, 807),\n (37, 2, 1451),\n (7, 73, 754),\n (47, 86, 184),\n (67, 17, 449),\n (18, 67, 803),\n (25, 4, 595),\n (3, 31, 1337),\n (64, 31, 1928),\n (9, 43, 237),\n (83, 63, 1604),\n (47, 45, 272),\n (86, 88, 574),\n (87, 74, 934),\n (98, 94, 646),\n (20, 1, 642),\n (26, 92, 1344),\n (18, 17, 565),\n (47, 11, 595),\n (10, 59, 1558),\n (2, 76, 1658),\n (77, 74, 1277),\n (42, 60, 477),\n (80, 36, 395),\n (35, 23, 589),\n (50, 37, 203),\n (6, 96, 481),\n (78, 65, 1052),\n (1, 52, 127),\n (65, 23, 1932),\n (46, 51, 213),\n (59, 89, 89),\n (15, 93, 1462),\n (69, 3, 1305),\n (17, 37, 1177),\n (30, 3, 193),\n (9, 15, 818),\n (75, 95, 977),\n (86, 47, 184),\n (10, 12, 1736),\n (80, 27, 1010),\n (12, 10, 1736),\n (86, 1, 1958),\n (60, 12, 1240),\n (43, 71, 683),\n (91, 65, 1519),\n (33, 86, 1649),\n (62, 26, 1773),\n (1, 13, 1187),\n (2, 10, 1018),\n (91, 29, 351),\n (69, 12, 136),\n (43, 9, 237),\n (29, 86, 258),\n (17, 48, 1807),\n (31, 64, 1928),\n (68, 61, 1936),\n (76, 38, 1724),\n (1, 6, 482),\n (53, 14, 355),\n (51, 50, 917),\n (54, 13, 815),\n (19, 29, 883),\n (35, 87, 974),\n (70, 96, 511),\n (23, 35, 589),\n (39, 69, 1588),\n (93, 73, 1093),\n (13, 73, 435),\n (5, 60, 1619),\n (42, 41, 1523),\n (66, 58, 1596),\n (1, 67, 431),\n (17, 67, 449),\n (30, 95, 906),\n (71, 43, 683),\n (5, 87, 190),\n (12, 78, 891),\n (30, 97, 402),\n (28, 17, 1131),\n (7, 97, 1356),\n (58, 66, 1596),\n (20, 37, 1294),\n (73, 76, 514),\n (54, 8, 613),\n (68, 35, 1252),\n (92, 32, 701),\n (3, 90, 652),\n (99, 46, 1576),\n (13, 54, 815),\n (20, 87, 1390),\n (36, 18, 1626),\n (51, 26, 1146),\n (2, 23, 581),\n (29, 7, 1558),\n (88, 59, 173),\n (17, 1, 1071),\n (37, 49, 1011),\n (18, 6, 696),\n (88, 33, 225),\n (58, 38, 802),\n (87, 50, 1744),\n (29, 91, 351),\n (6, 71, 1053),\n (45, 24, 1720),\n (65, 91, 1519),\n (37, 50, 203),\n (11, 3, 943),\n (72, 65, 1330),\n (45, 50, 339),\n (25, 20, 971),\n (15, 9, 818),\n (14, 54, 1353),\n (69, 95, 393),\n (8, 66, 1213),\n (52, 2, 1608),\n (50, 14, 690),\n (50, 45, 339),\n (1, 37, 1273),\n (45, 93, 1650),\n (39, 78, 313),\n (1, 86, 1958),\n (17, 28, 1131),\n (35, 33, 1667),\n (23, 2, 581),\n (51, 66, 245),\n (17, 54, 924),\n (41, 49, 1629),\n (60, 5, 1619),\n (56, 93, 1110),\n (96, 13, 461),\n (25, 7, 637),\n (11, 69, 370),\n (90, 3, 652),\n (39, 71, 1485),\n (65, 51, 1529),\n (20, 6, 1414),\n (80, 85, 270),\n (73, 83, 1162),\n (0, 97, 1303),\n (13, 33, 826),\n (29, 71, 1788),\n (33, 12, 461),\n (12, 58, 1273),\n (69, 39, 1588),\n (67, 75, 1504),\n (87, 20, 1390),\n (88, 97, 526),\n (33, 88, 225),\n (95, 69, 393),\n (2, 52, 1608),\n (5, 25, 719),\n (34, 78, 510),\n (53, 99, 1074),\n (33, 35, 1667),\n (57, 30, 361),\n (87, 58, 1574),\n (13, 90, 1030),\n (79, 74, 91),\n (4, 86, 1107),\n (64, 94, 1609),\n (11, 12, 167),\n (30, 45, 272),\n (47, 91, 561),\n (37, 17, 1177),\n (77, 49, 883),\n (88, 23, 1747),\n (70, 80, 995),\n (62, 77, 907),\n (18, 4, 371),\n (73, 93, 1093),\n (11, 47, 595),\n (44, 23, 1990),\n (20, 0, 512),\n (3, 69, 1305),\n (82, 3, 1815),\n (20, 88, 368),\n (44, 45, 364),\n (26, 51, 1146),\n (7, 65, 349),\n (71, 39, 1485),\n (56, 88, 1954),\n (94, 69, 1397),\n (12, 28, 544),\n (95, 75, 977),\n (32, 90, 789),\n (53, 1, 772),\n (54, 14, 1353),\n (49, 77, 883),\n (92, 26, 1344),\n (17, 18, 565),\n (97, 88, 526),\n (48, 80, 1203),\n (90, 32, 789),\n (71, 6, 1053),\n (87, 35, 974),\n (55, 90, 1808),\n (12, 61, 1791),\n (1, 96, 328),\n (63, 10, 1681),\n (76, 34, 871),\n (41, 64, 926),\n (42, 97, 482),\n (25, 5, 719),\n (23, 65, 1932),\n (54, 1, 1491),\n (28, 12, 544),\n (89, 10, 108),\n (27, 33, 143),\n (67, 1, 431),\n (32, 45, 52),\n (79, 33, 1871),\n (6, 55, 717),\n (10, 58, 459),\n (67, 39, 393),\n (10, 4, 1808),\n (96, 6, 481),\n (1, 19, 970),\n (97, 7, 1356),\n (29, 16, 1108),\n (1, 53, 772),\n (30, 15, 1125),\n (4, 6, 634),\n (6, 20, 1414),\n (88, 56, 1954),\n (87, 64, 1950),\n (34, 76, 871),\n (17, 12, 285),\n (55, 59, 321),\n (61, 68, 1936),\n (50, 87, 1744),\n (84, 44, 952),\n (41, 33, 993),\n (59, 18, 1352),\n (33, 27, 143),\n (38, 32, 1210),\n (55, 70, 1264),\n (38, 58, 802),\n (1, 20, 642),\n (73, 13, 435),\n (80, 48, 1203),\n (94, 64, 1609),\n (38, 28, 414),\n (73, 23, 1113),\n (78, 12, 891),\n (26, 62, 1773),\n (87, 43, 579),\n (53, 6, 95),\n (59, 95, 285),\n (88, 63, 1717),\n (17, 5, 633),\n (66, 8, 1213),\n (41, 42, 1523),\n (83, 22, 597),\n (95, 30, 906),\n (51, 65, 1529),\n (17, 49, 1727),\n (64, 87, 1950),\n (86, 4, 1107),\n (37, 98, 1102),\n (32, 92, 701),\n (60, 94, 198),\n (73, 98, 1749),\n (4, 18, 371),\n (96, 70, 511),\n (7, 29, 1558),\n (35, 37, 841),\n (27, 64, 384),\n (12, 33, 461),\n (36, 38, 529),\n (69, 16, 1183),\n (91, 47, 561),\n (85, 29, 1676),\n (3, 82, 1815),\n (69, 58, 1579),\n (93, 45, 1650),\n (97, 42, 482),\n (37, 1, 1273),\n (61, 4, 543),\n (96, 1, 328),\n (26, 0, 1993),\n (70, 64, 878),\n (3, 30, 193),\n (58, 69, 1579),\n (4, 25, 595),\n (31, 3, 1337),\n (55, 6, 717),\n (39, 67, 393),\n (78, 34, 510),\n (75, 67, 1504),\n (6, 53, 95),\n (51, 79, 175),\n (28, 91, 1040),\n (89, 78, 1828),\n (74, 93, 1587),\n (45, 32, 52),\n (10, 2, 1018),\n (49, 37, 1011),\n (63, 61, 845),\n (0, 20, 512),\n (1, 17, 1071),\n (99, 53, 1074),\n (37, 20, 1294),\n (10, 89, 108),\n (33, 92, 946),\n (23, 73, 1113),\n (23, 88, 1747),\n (49, 17, 1727),\n (88, 20, 368),\n (21, 54, 1870),\n (70, 93, 1582),\n (59, 88, 173),\n (32, 38, 1210),\n (89, 59, 89),\n (23, 44, 1990),\n (38, 76, 1724),\n (30, 57, 361),\n (94, 60, 198),\n (59, 10, 1558),\n (55, 64, 1996),\n (12, 11, 167),\n (36, 24, 1801),\n (97, 30, 402),\n (52, 1, 127),\n (58, 87, 1574),\n (54, 17, 924),\n (93, 74, 1587),\n (24, 36, 1801),\n (2, 37, 1451),\n (91, 28, 1040),\n (59, 55, 321),\n (69, 11, 370),\n (8, 54, 613),\n (29, 85, 1676),\n (44, 19, 1762),\n (74, 79, 91),\n (93, 56, 1110),\n (58, 10, 459),\n (41, 50, 1559),\n (66, 51, 245),\n (80, 19, 1838),\n (33, 79, 1871),\n (76, 73, 514),\n (98, 37, 1102),\n (45, 44, 364),\n (16, 69, 1183),\n (49, 41, 1629),\n (19, 80, 1838),\n (71, 57, 500),\n (6, 4, 634),\n (64, 27, 384),\n (84, 86, 1431),\n (5, 17, 633),\n (96, 88, 334),\n (87, 5, 190),\n (70, 21, 1619),\n (55, 33, 1391),\n (10, 63, 1681),\n (11, 62, 1339),\n (33, 13, 826),\n (64, 70, 878),\n (65, 72, 1330),\n (70, 55, 1264),\n (64, 55, 1996),\n (50, 41, 1559),\n (46, 99, 1576),\n (88, 96, 334),\n (51, 20, 868),\n (73, 7, 754),\n (80, 70, 995),\n (44, 84, 952),\n (29, 19, 883),\n (59, 69, 903),\n (57, 53, 1575),\n (90, 13, 1030),\n (28, 38, 414),\n (12, 60, 1240),\n (85, 58, 573),\n (90, 55, 1808),\n (4, 10, 1808),\n (68, 44, 1229),\n (92, 33, 946),\n (90, 81, 1024),\n (53, 75, 545),\n (45, 30, 272),\n (41, 77, 138),\n (21, 70, 1619),\n (45, 73, 1876),\n (35, 68, 1252),\n (13, 96, 461),\n (53, 57, 1575),\n (82, 89, 409),\n (28, 61, 449),\n (58, 61, 78),\n (27, 80, 1010),\n (61, 58, 78),\n (38, 36, 529),\n (80, 30, 397),\n (18, 59, 1352),\n (62, 11, 1339),\n (95, 59, 285),\n (51, 98, 1160),\n (6, 18, 696),\n (30, 80, 397),\n (69, 94, 1397),\n (58, 85, 573),\n (48, 99, 410),\n (51, 46, 213),\n (57, 71, 500),\n (91, 30, 104),\n (65, 7, 349),\n (79, 51, 175),\n (47, 26, 921),\n (4, 61, 543),\n (98, 73, 1749),\n (74, 77, 1277),\n (61, 28, 449),\n (58, 8, 1131),\n (61, 45, 1608),\n (74, 87, 934),\n (71, 29, 1788),\n (30, 91, 104),\n (13, 1, 1187),\n (0, 26, 1993),\n (82, 49, 1292),\n (43, 87, 579),\n (24, 45, 1720),\n (20, 51, 868),\n (77, 62, 907),\n (82, 75, 306),\n]\n\nstruct PrimsState<Node: GraphNode, Box> where Node.BoxType == Box, Box.ValueType == Node {\n var graph: Array<Node>\n var edgeToCostMap: Dictionary<Edge<Node>, Double>\n\n init(_ _: Node.Type) {\n // Prepare graph and edge->cost map\n graph = Array<Node>()\n for nodeId in nodes {\n graph.append(Node(id: nodeId))\n }\n\n edgeToCostMap = Dictionary<Edge<Node>, Double>()\n for tup in edges {\n edgeToCostMap[Edge(start: Box(graph[tup.0]), end: Box(graph[tup.1]))] = tup.2\n graph[tup.0].adjList.append(Box(graph[tup.1]))\n }\n }\n}\n\nlet weakPrimsState = PrimsState(WeakGraphNode.self)\nlet unownedSafePrimsState = PrimsState(UnownedSafeGraphNode.self)\nlet unownedUnsafePrimsState = PrimsState(UnownedUnsafeGraphNode.self)\nlet unmanagedPrimsState = PrimsState(UnmanagedGraphNode.self)\nlet unmanagedUGRPrimsState = PrimsState(UnmanagedUGRGraphNode.self)\n\n//===----------------------------------------------------------------------===//\n// Protocols\n//===----------------------------------------------------------------------===//\n\nprotocol ValueBox : Hashable {\n associatedtype ValueType : AnyObject\n\n init(_ inputValue: ValueType)\n var value: ValueType { get }\n\n func withValue<Result>(_ f: (ValueType) throws -> Result) rethrows -> Result\n func free()\n}\n\nextension ValueBox {\n func free() {}\n @_transparent\n func withValue<Result>(_ f: (ValueType) throws -> Result) rethrows -> Result {\n return try f(value)\n }\n}\n\nprotocol GraphNode {\n associatedtype BoxType : ValueBox where BoxType.ValueType == Self\n\n init(id inputId: Int)\n var id: Int { get }\n var adjList: Array<BoxType> { get set }\n}\n\n//===----------------------------------------------------------------------===//\n// Box Implementations\n//===----------------------------------------------------------------------===//\n\nstruct WeakVarBox<T : AnyObject & Hashable> {\n weak var _value: T?\n\n init(_ inputValue: T) {\n _value = inputValue\n }\n}\n\nextension WeakVarBox : ValueBox where T : GraphNode {\n typealias ValueType = T\n\n var value: T {\n return _value!\n }\n}\n\nextension WeakVarBox : Equatable where T : Equatable {}\nextension WeakVarBox : Hashable where T : Hashable {}\n\nstruct UnownedSafeVarBox<T : AnyObject & Hashable> {\n unowned var value: T\n\n init(_ inputValue: T) {\n value = inputValue\n }\n}\n\nextension UnownedSafeVarBox : ValueBox where T : GraphNode {\n typealias ValueType = T\n}\n\nextension UnownedSafeVarBox : Equatable where T : Equatable {}\nextension UnownedSafeVarBox : Hashable where T : Hashable {}\n\nstruct UnownedUnsafeVarBox<T : AnyObject & Hashable> {\n unowned(unsafe) var value: T\n\n init(_ inputValue: T) {\n value = inputValue\n }\n}\n\nextension UnownedUnsafeVarBox : ValueBox where T : GraphNode {\n typealias ValueType = T\n}\n\nextension UnownedUnsafeVarBox : Equatable where T : Equatable {}\nextension UnownedUnsafeVarBox : Hashable where T : Hashable {}\n\nstruct UnmanagedVarBox<T : AnyObject & Hashable> {\n var _value: Unmanaged<T>\n\n var value: T { return _value.takeUnretainedValue() }\n\n init(_ inputValue: T) {\n _value = Unmanaged<T>.passRetained(inputValue)\n }\n}\n\nextension UnmanagedVarBox : ValueBox where T : GraphNode {\n typealias ValueType = T\n\n func free() {\n _value.release()\n }\n}\n\nextension UnmanagedVarBox : Equatable where T : Equatable {\n}\n\nfunc ==<T>(lhs: UnmanagedVarBox<T>, rhs: UnmanagedVarBox<T>) -> Bool {\n return lhs.value === rhs.value\n}\n\nextension UnmanagedVarBox : Hashable where T : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(value))\n }\n}\n\nstruct UnmanagedUGRVarBox<T : AnyObject & Hashable> {\n var _value: Unmanaged<T>\n\n init(_ inputValue: T) {\n _value = Unmanaged<T>.passRetained(inputValue)\n }\n}\n\nextension UnmanagedUGRVarBox : ValueBox where T : GraphNode {\n typealias ValueType = T\n\n func free() {\n _value.release()\n }\n\n var value: T { return _value._withUnsafeGuaranteedRef { $0 } }\n\n func withValue<Result>(_ f: (ValueType) throws -> Result) rethrows -> Result {\n try _value._withUnsafeGuaranteedRef { try f($0) }\n }\n}\n\nextension UnmanagedUGRVarBox : Equatable where T : Equatable {\n}\n\nfunc ==<T>(lhs: UnmanagedUGRVarBox<T>, rhs: UnmanagedUGRVarBox<T>) -> Bool {\n return lhs._value._withUnsafeGuaranteedRef { x in\n return rhs._value._withUnsafeGuaranteedRef { y in\n return x == y\n }}\n}\n\nextension UnmanagedUGRVarBox : Hashable where T : Hashable {\n func hash(into hasher: inout Hasher) {\n _value._withUnsafeGuaranteedRef {\n hasher.combine(ObjectIdentifier($0))\n }\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Graph Node Implementations\n//===----------------------------------------------------------------------===//\n\nfinal class WeakGraphNode {\n /// This id is only meant for dumping the state of the graph. It is not meant\n /// to be used functionally by the algorithm.\n var id: Int\n\n var adjList: Array<WeakVarBox<WeakGraphNode>>\n\n init(id inputId: Int) {\n id = inputId\n adjList = Array<WeakVarBox<WeakGraphNode>>()\n }\n}\n\nextension WeakGraphNode : GraphNode {\n typealias BoxType = WeakVarBox<WeakGraphNode>\n}\n\nextension WeakGraphNode : Equatable {}\nextension WeakGraphNode : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n}\n\nfunc ==(lhs: WeakGraphNode, rhs: WeakGraphNode) -> Bool {\n return lhs === rhs\n}\n\nfinal class UnownedSafeGraphNode {\n /// This id is only meant for dumping the state of the graph. It is not meant\n /// to be used functionally by the algorithm.\n var id: Int\n\n var adjList: Array<UnownedSafeVarBox<UnownedSafeGraphNode>>\n\n init(id inputId: Int) {\n id = inputId\n adjList = Array<UnownedSafeVarBox<UnownedSafeGraphNode>>()\n }\n}\n\nextension UnownedSafeGraphNode : GraphNode {\n typealias BoxType = UnownedSafeVarBox<UnownedSafeGraphNode>\n}\n\nextension UnownedSafeGraphNode : Equatable {}\nextension UnownedSafeGraphNode : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n}\n\nfinal class UnownedUnsafeGraphNode {\n /// This id is only meant for dumping the state of the graph. It is not meant\n /// to be used functionally by the algorithm.\n var id: Int\n\n var adjList: Array<UnownedUnsafeVarBox<UnownedUnsafeGraphNode>>\n\n init(id inputId: Int) {\n id = inputId\n adjList = Array<UnownedUnsafeVarBox<UnownedUnsafeGraphNode>>()\n }\n}\n\nfunc ==(lhs: UnownedSafeGraphNode, rhs: UnownedSafeGraphNode) -> Bool {\n return lhs === rhs\n}\n\nextension UnownedUnsafeGraphNode : GraphNode {\n typealias BoxType = UnownedUnsafeVarBox<UnownedUnsafeGraphNode>\n}\n\nextension UnownedUnsafeGraphNode : Equatable {}\nextension UnownedUnsafeGraphNode : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n}\n\nfunc ==(lhs: UnownedUnsafeGraphNode, rhs: UnownedUnsafeGraphNode) -> Bool {\n return lhs === rhs\n}\n\nfinal class UnmanagedGraphNode {\n /// This id is only meant for dumping the state of the graph. It is not meant\n /// to be used functionally by the algorithm.\n var id: Int\n\n var adjList: Array<UnmanagedVarBox<UnmanagedGraphNode>>\n\n init(id inputId: Int) {\n id = inputId\n adjList = Array<UnmanagedVarBox<UnmanagedGraphNode>>()\n }\n\n deinit {\n for x in adjList {\n x.free()\n }\n }\n}\n\nextension UnmanagedGraphNode : GraphNode {\n typealias BoxType = UnmanagedVarBox<UnmanagedGraphNode>\n}\n\nextension UnmanagedGraphNode : Equatable {}\nextension UnmanagedGraphNode : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n}\n\nfunc ==(lhs: UnmanagedGraphNode, rhs: UnmanagedGraphNode) -> Bool {\n return lhs === rhs\n}\n\n\nfinal class UnmanagedUGRGraphNode {\n /// This id is only meant for dumping the state of the graph. It is not meant\n /// to be used functionally by the algorithm.\n var id: Int\n\n var adjList: Array<UnmanagedUGRVarBox<UnmanagedUGRGraphNode>>\n\n init(id inputId: Int) {\n id = inputId\n adjList = Array<UnmanagedUGRVarBox<UnmanagedUGRGraphNode>>()\n }\n\n deinit {\n for x in adjList {\n x.free()\n }\n }\n}\n\nextension UnmanagedUGRGraphNode : GraphNode {\n typealias BoxType = UnmanagedUGRVarBox<UnmanagedUGRGraphNode>\n}\n\nextension UnmanagedUGRGraphNode : Equatable {}\nextension UnmanagedUGRGraphNode : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self))\n }\n}\n\nfunc ==(lhs: UnmanagedUGRGraphNode, rhs: UnmanagedUGRGraphNode) -> Bool {\n return lhs === rhs\n}\n\n//===----------------------------------------------------------------------===//\n// Edge Implementation\n//===----------------------------------------------------------------------===//\n\nstruct Edge<Node : GraphNode> {\n var start: Node.BoxType\n var end: Node.BoxType\n}\n\nextension Edge : Equatable {}\n\nfunc ==<Node>(lhs: Edge<Node>, rhs: Edge<Node>) -> Bool {\n return lhs.start == rhs.start && lhs.end == rhs.end\n}\n\nextension Edge : Hashable {\n func hash(into hasher: inout Hasher) {\n hasher.combine(start)\n hasher.combine(end)\n }\n}\n\n//===----------------------------------------------------------------------===//\n// Algorithm\n//===----------------------------------------------------------------------===//\n\nclass PriorityQueue<Node : GraphNode> {\n final var heap: Array<EdgeCost<Node, Node.BoxType>>\n final var graphIndexToHeapIndexMap: Dictionary<Node.BoxType, Int>\n\n // Create heap for graph with NUM nodes.\n init(count: Int) {\n heap = Array<EdgeCost<Node, Node.BoxType>>()\n graphIndexToHeapIndexMap = Dictionary<Node.BoxType, Int>()\n }\n\n var isEmpty: Bool { return heap.isEmpty }\n\n // Insert element N to heap, maintaining the heap property.\n func insert(_ n: EdgeCost<Node, Node.BoxType>) {\n let ind: Int = heap.count\n heap.append(n)\n graphIndexToHeapIndexMap[n.to] = heap.count - 1\n bubbleUp(ind)\n }\n\n // Insert element N if in's not in the heap, or update its cost if the new\n // value is less than the existing one.\n func insertOrUpdate(_ n: EdgeCost<Node, Node.BoxType>) {\n let id = n.to\n let c = n.cost\n if let ind = graphIndexToHeapIndexMap[id] {\n if heap[ind].cost <= c {\n // We don't need an edge with a bigger cost\n return\n }\n heap[ind].cost = c\n heap[ind].from = n.from\n bubbleUp(ind)\n } else {\n insert(n)\n }\n }\n\n // Restore heap property by moving element at index IND up.\n // This is needed after insertion, and after decreasing an element's cost.\n func bubbleUp(_ ind: Int) {\n var ind = ind\n let c = heap[ind].cost\n while (ind != 0) {\n let p = getParentIndex(ind)\n if heap[p].cost > c {\n swap(p, with: ind)\n ind = p\n } else {\n break\n }\n }\n }\n\n // Pop minimum element from heap and restore the heap property after that.\n func pop() -> EdgeCost<Node, Node.BoxType>? {\n if (heap.isEmpty) {\n return nil\n }\n swap(0, with:heap.count-1)\n let r = heap.removeLast()\n graphIndexToHeapIndexMap[r.to] = nil\n bubbleDown(0)\n return r\n }\n\n // Restore heap property by moving element at index IND down.\n // This is needed after removing an element, and after increasing an\n // element's cost.\n func bubbleDown(_ ind: Int) {\n var ind = ind\n let n = heap.count\n while (ind < n) {\n let l = getLeftChildIndex(ind)\n let r = getRightChildIndex(ind)\n if (l >= n) {\n break\n }\n var min: Int\n if (r < n && heap[r].cost < heap[l].cost) {\n min = r\n } else {\n min = l\n }\n if (heap[ind].cost <= heap[min].cost) {\n break\n }\n swap(ind, with: min)\n ind = min\n }\n }\n\n // Swaps elements I and J in the heap and correspondingly updates\n // graphIndexToHeapIndexMap.\n func swap(_ i: Int, with j : Int) {\n if (i == j) {\n return\n }\n (heap[i], heap[j]) = (heap[j], heap[i])\n let (I, J) = (heap[i].to, heap[j].to)\n (graphIndexToHeapIndexMap[I], graphIndexToHeapIndexMap[J]) =\n (graphIndexToHeapIndexMap[J], graphIndexToHeapIndexMap[I])\n }\n\n // Dumps the heap.\n func dump() {\n print("QUEUE")\n for nodeCost in heap {\n let to: Int = nodeCost.to.value.id\n let from: Int = nodeCost.from.value.id\n let cost: Double = nodeCost.cost\n print("(\(from)->\(to), \(cost))")\n }\n }\n\n func getLeftChildIndex(_ index : Int) -> Int {\n return index*2 + 1\n }\n func getRightChildIndex(_ index : Int) -> Int {\n return (index + 1)*2\n }\n func getParentIndex(_ childIndex : Int) -> Int {\n return (childIndex - 1)/2\n }\n}\n\nstruct EdgeCost<Node : GraphNode, Box> where Node.BoxType == Box, Box.ValueType == Node {\n var to: Box\n var cost: Double\n var from: Box\n\n init(to inputTo: Node, cost inputCost: Double, from inputFrom: Node) {\n to = Box(inputTo)\n cost = inputCost\n from = Box(inputFrom)\n }\n\n init(to inputTo: Box, cost inputCost: Double, from inputFrom: Box) {\n to = inputTo\n cost = inputCost\n from = inputFrom\n }\n}\n\nfunc primsMainLoop<Node : GraphNode, Box>(\n _ graph : Array<Node>,\n _ fun : (Node.BoxType, Node.BoxType) -> Double) -> Array<Int?>\nwhere Node.BoxType == Box, Box.ValueType == Node\n{\n var treeEdges = Array<Int?>(repeating:nil, count:graph.count)\n let queue = PriorityQueue<Node>(count: graph.count)\n\n // Make the minimum spanning tree root its own parent for simplicity.\n queue.insert(EdgeCost(to: graph[0], cost: 0.0, from: graph[0]))\n\n // Take an element with the smallest cost from the queue and add its\n // neighbors to the queue if their cost was updated\n while !queue.isEmpty {\n // Add an edge with minimum cost to the spanning tree\n let e = queue.pop()!\n let newnode: Node.BoxType = e.to\n\n // Add record about the edge newnode->e.from to treeEdges\n treeEdges[newnode.value.id] = e.from.value.id\n\n // Check all adjacent nodes and add edges, ending outside the tree, to the\n // queue. If the queue already contains an edge to an adjacent node, we\n // replace existing one with the new one in case the new one costs less.\n for toNode: Box in newnode.value.adjList {\n if treeEdges[toNode.value.id] != nil {\n continue\n }\n let newcost = fun(newnode, toNode)\n queue.insertOrUpdate(EdgeCost(to: toNode, cost: newcost, from: newnode))\n }\n }\n return treeEdges\n}\n\nfunc primsMainLoopClosureAccess<Node : GraphNode, Box>(\n _ graph : Array<Node>,\n _ fun : (Node.BoxType, Node.BoxType) -> Double) -> Array<Int?>\nwhere Node.BoxType == Box, Box.ValueType == Node\n{\n var treeEdges = Array<Int?>(repeating:nil, count:graph.count)\n let queue = PriorityQueue<Node>(count: graph.count)\n\n // Make the minimum spanning tree root its own parent for simplicity.\n queue.insert(EdgeCost(to: graph[0], cost: 0.0, from: graph[0]))\n\n // Take an element with the smallest cost from the queue and add its\n // neighbors to the queue if their cost was updated\n while !queue.isEmpty {\n // Add an edge with minimum cost to the spanning tree\n let e = queue.pop()!\n let newnode: Node.BoxType = e.to\n\n // Add record about the edge newnode->e.from to treeEdges\n treeEdges[newnode.withValue { $0.id }] = e.from.withValue { $0.id }\n\n // Check all adjacent nodes and add edges, ending outside the tree, to the\n // queue. If the queue already contains an edge to an adjacent node, we\n // replace existing one with the new one in case the new one costs less.\n for toNode: Box in (newnode.withValue { $0.adjList }) {\n if treeEdges[toNode.withValue({ $0.id })] != nil {\n continue\n }\n let newcost = fun(newnode, toNode)\n queue.insertOrUpdate(EdgeCost(to: toNode, cost: newcost, from: newnode))\n }\n }\n return treeEdges\n}\n\n//===----------------------------------------------------------------------===//\n// Top Level Entrypoints\n//===----------------------------------------------------------------------===//\n\n\n@inline(__always)\nfunc run_PrimsNonStrongRef<Node: GraphNode, Box>(_ state: PrimsState<Node, Box>) where Node.BoxType == Box, Box.ValueType == Node {\n let graph = state.graph\n let map = state.edgeToCostMap\n\n // Find spanning tree\n let treeEdges = primsMainLoop(graph, { (start: Box, end: Box) in\n return map[Edge(start: start, end: end)]!\n })\n\n // Compute its cost in order to check results\n var cost = 0.0\n for i in 1..<treeEdges.count {\n if let n = treeEdges[i] {\n cost += map[Edge(start: Box(graph[n]), end: Box(graph[i]))]!\n }\n }\n check(Int(cost) == 49324)\n}\n\n@inline(__always)\nfunc run_PrimsNonStrongRefClosureAccess<Node: GraphNode, Box>(_ state: PrimsState<Node, Box>) where Node.BoxType == Box, Box.ValueType == Node {\n let graph = state.graph\n let map = state.edgeToCostMap\n\n // Find spanning tree\n let treeEdges = primsMainLoopClosureAccess(graph, { (start: Box, end: Box) in\n return map[Edge(start: start, end: end)]!\n })\n\n // Compute its cost in order to check results\n var cost = 0.0\n for i in 1..<treeEdges.count {\n if let n = treeEdges[i] {\n cost += map[Edge(start: Box(graph[n]), end: Box(graph[i]))]!\n }\n }\n check(Int(cost) == 49324)\n}\n\n\n@inline(never)\npublic func run_PrimsWeak(_ n: Int) {\n let state = weakPrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRef(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsWeakClosureAccess(_ n: Int) {\n let state = weakPrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRefClosureAccess(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsUnownedSafe(_ n: Int) {\n let state = unownedSafePrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRef(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsUnownedSafeClosureAccess(_ n: Int) {\n let state = unownedSafePrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRefClosureAccess(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsUnownedUnsafe(_ n: Int) {\n let state = unownedUnsafePrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRef(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsUnownedUnsafeClosureAccess(_ n: Int) {\n let state = unownedUnsafePrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRefClosureAccess(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsUnmanaged(_ n: Int) {\n let state = unmanagedPrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRef(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsUnmanagedClosureAccess(_ n: Int) {\n let state = unmanagedPrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRefClosureAccess(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsUnmanagedUGR(_ n: Int) {\n let state = unmanagedUGRPrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRef(state)\n }\n}\n\n@inline(never)\npublic func run_PrimsUnmanagedUGRClosureAccess(_ n: Int) {\n let state = unmanagedUGRPrimsState\n for _ in 0..<n {\n run_PrimsNonStrongRefClosureAccess(state)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_PrimsNonStrongRef.swift | cpp_apple_swift_benchmark_single-source_PrimsNonStrongRef.swift | Swift | 32,977 | 0.95 | 0.049034 | 0.084774 | node-utils | 481 | 2025-07-03T23:21:00.095747 | MIT | false | 51e802dd1232d60cc58f92f096930744 |
//===--- ProtocolDispatch.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo (\n name: "ProtocolConformance",\n runFunction: run_ProtocolConformance,\n tags: [.validation, .runtime])\n\nprotocol P {}\n\nstruct One: P {}\nstruct Two {}\n\nstruct Cat<T, U> {}\n\nextension Cat: P where T: P, U: P {}\n\nprotocol Growable {}\nextension Growable {\n func grow() -> (Growable, Growable) {\n return (Cat<Self, One>(), Cat<Self, Two>())\n }\n}\n\nextension One: Growable {}\nextension Two: Growable {}\nextension Cat: Growable {}\n\n@inline(never)\npublic func run_ProtocolConformance(_ n: Int) {\n var array: [Growable] = [One(), Two()]\n var i = 0\n var checks = 0\n\n // The expected number of times we expect `elt is P` to be true.\n var expectedConforms = 0\n\n // The expected number of times we expect `elt is P` to be true\n // per iteration, at the current time.\n var expectedConformsPerIter = 1\n\n // The number of times we've actually seen `elt is P` be true.\n var conforms = 0\n while checks < n * 500 {\n let (a, b) = array[i].grow()\n array.append(a)\n array.append(b)\n\n // The number of times `elt is P` is true per outer iteration\n // goes up by 1 when the array's count is a power of 2.\n if array.count & (array.count - 1) == 0 {\n expectedConformsPerIter += 1\n }\n expectedConforms += expectedConformsPerIter\n\n for elt in array {\n if elt is P {\n conforms += 1\n }\n checks += 1\n }\n i += 1\n }\n check(expectedConforms == conforms)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ProtocolConformance.swift | cpp_apple_swift_benchmark_single-source_ProtocolConformance.swift | Swift | 1,987 | 0.95 | 0.077922 | 0.269841 | vue-tools | 768 | 2024-07-01T12:58:42.826317 | Apache-2.0 | false | bdc4685af247c9bc59a276bb118765dd |
// Radix2CooleyTukey benchmark\n//\n// Originally written by @owensd. Used with his permission.\n\n#if canImport(Glibc)\nimport Glibc\n#elseif canImport(Musl)\nimport Musl\n#elseif os(Windows)\nimport MSVCRT\n#else\nimport Darwin\n#endif\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "Radix2CooleyTukey",\n runFunction: run_Radix2CooleyTukey,\n tags: [.validation, .algorithm],\n setUpFunction: setUpRadix2CooleyTukey,\n tearDownFunction: tearDownRadix2CooleyTukey,\n legacyFactor: 48),\n BenchmarkInfo(\n name: "Radix2CooleyTukeyf",\n runFunction: run_Radix2CooleyTukeyf,\n tags: [.validation, .algorithm],\n setUpFunction: setUpRadix2CooleyTukeyf,\n tearDownFunction: tearDownRadix2CooleyTukeyf,\n legacyFactor: 48),\n]\n\n//===----------------------------------------------------------------------===//\n// Double Benchmark\n//===----------------------------------------------------------------------===//\n\nvar double_input_real: UnsafeMutablePointer<Double>?\nvar double_input_imag: UnsafeMutablePointer<Double>?\nvar double_output_real: UnsafeMutablePointer<Double>?\nvar double_output_imag: UnsafeMutablePointer<Double>?\nvar double_temp_real: UnsafeMutablePointer<Double>?\nvar double_temp_imag: UnsafeMutablePointer<Double>?\n\nlet doubleN = 2_048\nlet doubleSize = { MemoryLayout<Double>.size * doubleN }()\n\nfunc setUpRadix2CooleyTukey() {\n let size = doubleSize\n\n double_input_real = UnsafeMutablePointer<Double>.allocate(capacity: size)\n double_input_imag = UnsafeMutablePointer<Double>.allocate(capacity: size)\n double_output_real = UnsafeMutablePointer<Double>.allocate(capacity: size)\n double_output_imag = UnsafeMutablePointer<Double>.allocate(capacity: size)\n double_temp_real = UnsafeMutablePointer<Double>.allocate(capacity: size)\n double_temp_imag = UnsafeMutablePointer<Double>.allocate(capacity: size)\n}\n\nfunc tearDownRadix2CooleyTukey() {\n double_input_real?.deallocate()\n double_input_imag?.deallocate()\n double_output_real?.deallocate()\n double_output_imag?.deallocate()\n double_temp_real?.deallocate()\n double_temp_imag?.deallocate()\n}\n\nfunc radix2CooleyTukey(_ level: Int,\n input_real: UnsafeMutablePointer<Double>,\n input_imag: UnsafeMutablePointer<Double>,\n stride: Int, output_real: UnsafeMutablePointer<Double>,\n output_imag: UnsafeMutablePointer<Double>,\n temp_real: UnsafeMutablePointer<Double>,\n temp_imag: UnsafeMutablePointer<Double>) {\n if level == 0 {\n output_real[0] = input_real[0];\n output_imag[0] = input_imag[0];\n return\n }\n let length = 1 << level\n let half = length >> 1\n radix2CooleyTukey(level - 1,\n input_real: input_real,\n input_imag: input_imag,\n stride: stride << 1,\n output_real: temp_real,\n output_imag: temp_imag,\n temp_real: output_real,\n temp_imag: output_imag)\n radix2CooleyTukey(level - 1,\n input_real: input_real + stride,\n input_imag: input_imag + stride,\n stride: stride << 1,\n output_real: temp_real + half,\n output_imag: temp_imag + half,\n temp_real: output_real + half,\n temp_imag: output_imag + half)\n for idx in 0..<half {\n let angle = -Double.pi * Double(idx) / Double(half)\n let _cos = cos(angle)\n let _sin = sin(angle)\n output_real[idx] = temp_real[idx] + _cos *\n temp_real[idx + half] - _sin * temp_imag[idx + half]\n output_imag[idx] = temp_imag[idx] + _cos *\n temp_imag[idx + half] + _sin *\n temp_real[idx + half]\n output_real[idx + half] = temp_real[idx] - _cos *\n temp_real[idx + half] + _sin *\n temp_imag[idx + half]\n output_imag[idx + half] = temp_imag[idx] - _cos *\n temp_imag[idx + half] - _sin *\n temp_real[idx + half]\n }\n}\n\nfunc testDouble(iter: Int) {\n let stride = 1\n\n let size = doubleSize\n let level = Int(log2(Double(doubleN)))\n\n let input_real = double_input_real.unsafelyUnwrapped\n let input_imag = double_input_imag.unsafelyUnwrapped\n let output_real = double_output_real.unsafelyUnwrapped\n let output_imag = double_output_imag.unsafelyUnwrapped\n let temp_real = double_temp_real.unsafelyUnwrapped\n let temp_imag = double_temp_imag.unsafelyUnwrapped\n\n for _ in 0..<iter {\n memset(UnsafeMutableRawPointer(input_real), 0, size)\n memset(UnsafeMutableRawPointer(input_imag), 0, size)\n memset(UnsafeMutableRawPointer(output_real), 0, size)\n memset(UnsafeMutableRawPointer(output_imag), 0, size)\n memset(UnsafeMutableRawPointer(temp_real), 0, size)\n memset(UnsafeMutableRawPointer(temp_imag), 0, size)\n\n radix2CooleyTukey(level,\n input_real: input_real,\n input_imag: input_imag,\n stride: stride,\n output_real: output_real,\n output_imag: output_imag,\n temp_real: temp_real,\n temp_imag: temp_imag)\n }\n}\n\n@inline(never)\npublic func run_Radix2CooleyTukey(_ n: Int) {\n testDouble(iter: n)\n}\n\n//===----------------------------------------------------------------------===//\n// Float Benchmark\n//===----------------------------------------------------------------------===//\n\nlet floatN = 2_048\nlet floatSize = { MemoryLayout<Float>.size * floatN }()\n\nvar float_input_real: UnsafeMutablePointer<Float>?\nvar float_input_imag: UnsafeMutablePointer<Float>?\nvar float_output_real: UnsafeMutablePointer<Float>?\nvar float_output_imag: UnsafeMutablePointer<Float>?\nvar float_temp_real: UnsafeMutablePointer<Float>?\nvar float_temp_imag: UnsafeMutablePointer<Float>?\n\nfunc setUpRadix2CooleyTukeyf() {\n let size = floatSize\n float_input_real = UnsafeMutablePointer<Float>.allocate(capacity: size)\n float_input_imag = UnsafeMutablePointer<Float>.allocate(capacity: size)\n float_output_real = UnsafeMutablePointer<Float>.allocate(capacity: size)\n float_output_imag = UnsafeMutablePointer<Float>.allocate(capacity: size)\n float_temp_real = UnsafeMutablePointer<Float>.allocate(capacity: size)\n float_temp_imag = UnsafeMutablePointer<Float>.allocate(capacity: size)\n}\n\nfunc tearDownRadix2CooleyTukeyf() {\n float_input_real?.deallocate()\n float_input_imag?.deallocate()\n float_output_real?.deallocate()\n float_output_imag?.deallocate()\n float_temp_real?.deallocate()\n float_temp_imag?.deallocate()\n}\n\nfunc radix2CooleyTukeyf(_ level: Int,\n input_real: UnsafeMutablePointer<Float>,\n input_imag: UnsafeMutablePointer<Float>,\n stride: Int, output_real: UnsafeMutablePointer<Float>,\n output_imag: UnsafeMutablePointer<Float>,\n temp_real: UnsafeMutablePointer<Float>,\n temp_imag: UnsafeMutablePointer<Float>) {\n if level == 0 {\n output_real[0] = input_real[0];\n output_imag[0] = input_imag[0];\n return\n }\n let length = 1 << level\n let half = length >> 1\n radix2CooleyTukeyf(level - 1,\n input_real: input_real,\n input_imag: input_imag,\n stride: stride << 1,\n output_real: temp_real,\n output_imag: temp_imag,\n temp_real: output_real,\n temp_imag: output_imag)\n radix2CooleyTukeyf(level - 1,\n input_real: input_real + stride,\n input_imag: input_imag + stride,\n stride: stride << 1,\n output_real: temp_real + half,\n output_imag: temp_imag + half,\n temp_real: output_real + half,\n temp_imag: output_imag + half)\n for idx in 0..<half {\n let angle = -Float.pi * Float(idx) / Float(half)\n let _cos = cosf(angle)\n let _sin = sinf(angle)\n output_real[idx] = temp_real[idx] + _cos *\n temp_real[idx + half] - _sin * temp_imag[idx + half]\n output_imag[idx] = temp_imag[idx] + _cos *\n temp_imag[idx + half] + _sin * temp_real[idx + half]\n output_real[idx + half] = temp_real[idx] - _cos *\n temp_real[idx + half] + _sin *\n temp_imag[idx + half]\n output_imag[idx + half] = temp_imag[idx] - _cos *\n temp_imag[idx + half] - _sin *\n temp_real[idx + half]\n }\n}\n\nfunc testFloat(iter: Int) {\n let stride = 1\n let n = floatN\n let size = floatSize\n\n let input_real = float_input_real.unsafelyUnwrapped\n let input_imag = float_input_imag.unsafelyUnwrapped\n let output_real = float_output_real.unsafelyUnwrapped\n let output_imag = float_output_imag.unsafelyUnwrapped\n let temp_real = float_temp_real.unsafelyUnwrapped\n let temp_imag = float_temp_imag.unsafelyUnwrapped\n\n let level = Int(log2(Float(n)))\n\n for _ in 0..<iter {\n memset(UnsafeMutableRawPointer(input_real), 0, size)\n memset(UnsafeMutableRawPointer(input_imag), 0, size)\n memset(UnsafeMutableRawPointer(output_real), 0, size)\n memset(UnsafeMutableRawPointer(output_imag), 0, size)\n memset(UnsafeMutableRawPointer(temp_real), 0, size)\n memset(UnsafeMutableRawPointer(temp_imag), 0, size)\n\n radix2CooleyTukeyf(level,\n input_real: input_real,\n input_imag: input_imag,\n stride: stride,\n output_real: output_real,\n output_imag: output_imag,\n temp_real: temp_real,\n temp_imag: temp_imag)\n }\n}\n\n@inline(never)\npublic func run_Radix2CooleyTukeyf(_ n: Int) {\n testFloat(iter: n)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Radix2CooleyTukey.swift | cpp_apple_swift_benchmark_single-source_Radix2CooleyTukey.swift | Swift | 8,755 | 0.95 | 0.026119 | 0.058091 | awesome-app | 754 | 2023-10-07T08:30:01.553652 | Apache-2.0 | false | 7eb98f486c7dbd44cd2a7415b0efdf8c |
//===--- RandomShuffle.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n//\n// Benchmark that shuffles arrays of integers. Measures the performance of\n// shuffling large arrays.\n//\n\npublic let benchmarks = [\n BenchmarkInfo(name: "RandomShuffleDef2", runFunction: run_RandomShuffleDef,\n tags: [.api], setUpFunction: { blackHole(numbersDef) }, legacyFactor: 4),\n BenchmarkInfo(name: "RandomShuffleLCG2", runFunction: run_RandomShuffleLCG,\n tags: [.api], setUpFunction: { blackHole(numbersLCG) }, legacyFactor: 16),\n]\n\n/// A linear congruential PRNG.\nstruct LCRNG: RandomNumberGenerator {\n private var state: UInt64\n\n init(seed: Int) {\n state = UInt64(truncatingIfNeeded: seed)\n for _ in 0..<10 { _ = next() }\n }\n\n mutating func next() -> UInt64 {\n state = 2862933555777941757 &* state &+ 3037000493\n return state\n }\n}\n\nvar numbersDef: [Int] = Array(0...2_500)\nvar numbersLCG: [Int] = Array(0...6_250)\n\n@inline(never)\npublic func run_RandomShuffleDef(_ n: Int) {\n for _ in 0 ..< n {\n numbersDef.shuffle()\n blackHole(numbersDef.first!)\n }\n}\n\n@inline(never)\npublic func run_RandomShuffleLCG(_ n: Int) {\n var generator = LCRNG(seed: 0)\n for _ in 0 ..< n {\n numbersLCG.shuffle(using: &generator)\n blackHole(numbersLCG.first!)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RandomShuffle.swift | cpp_apple_swift_benchmark_single-source_RandomShuffle.swift | Swift | 1,725 | 0.95 | 0.083333 | 0.313725 | vue-tools | 259 | 2024-01-10T16:48:14.563127 | Apache-2.0 | false | 8486d06b0700ead326b871b382e1d59e |
//===--- RandomTree.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test implements three competing versions of randomized binary trees,\n// indirectly testing reference counting performance.\n\nimport TestsUtils\n\nvar rng = SplitMix64(seed: 0)\nlet count = 400\nlet input = (0 ..< count).shuffled(using: &rng)\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "RandomTree.insert.ADT",\n runFunction: run_ADT_insert,\n tags: [.validation, .algorithm, .refcount],\n setUpFunction: { blackHole(input) }),\n BenchmarkInfo(\n name: "RandomTree.insert.Unmanaged.slow",\n runFunction: run_SlowUnmanaged_insert,\n tags: [.validation, .algorithm, .refcount],\n setUpFunction: { blackHole(input) }),\n BenchmarkInfo(\n name: "RandomTree.insert.Unmanaged.fast",\n runFunction: run_FastUnmanaged_insert,\n tags: [.validation, .algorithm, .refcount],\n setUpFunction: { blackHole(input) }),\n BenchmarkInfo(\n name: "RandomTree.insert.UnsafePointer",\n runFunction: run_UnsafePointer_insert,\n tags: [.validation, .algorithm, .refcount],\n setUpFunction: { blackHole(input) }),\n]\n\nenum EnumSearchTree<Element: Comparable> {\n case empty\n indirect case node(EnumSearchTree<Element>, Element, EnumSearchTree<Element>)\n}\n\nextension EnumSearchTree {\n func forEach(_ body: (Element) -> Void) {\n switch self {\n case .empty:\n break\n case let .node(left, value, right):\n left.forEach(body)\n body(value)\n right.forEach(body)\n }\n }\n\n func contains(_ value: Element) -> Bool {\n switch self {\n case .empty:\n return false\n case let .node(left, v, right):\n if value == v { return true }\n return value < v ? left.contains(value) : right.contains(value)\n }\n }\n\n func inserting(_ value: __owned Element) -> EnumSearchTree {\n switch self {\n case .empty:\n return .node(.empty, value, .empty)\n case let .node(left, root, right):\n if value == root {\n return self\n } else if value < root {\n return .node(left.inserting(value), root, right)\n } else {\n return .node(left, root, right.inserting(value))\n }\n }\n }\n}\n\nstruct SlowUnmanagedSearchTree<Element: Comparable> {\n class Node {\n var value: Element\n var left: SlowUnmanagedSearchTree\n var right: SlowUnmanagedSearchTree\n\n init(\n value: Element,\n left: SlowUnmanagedSearchTree = .empty,\n right: SlowUnmanagedSearchTree = .empty\n ) {\n self.left = left\n self.right = right\n self.value = value\n }\n }\n\n static var empty: SlowUnmanagedSearchTree<Element> { SlowUnmanagedSearchTree() }\n\n var root: Unmanaged<Node>?\n\n init() {\n self.root = nil\n }\n\n init(_root: Unmanaged<Node>?) {\n self.root = _root\n }\n}\n\nextension SlowUnmanagedSearchTree {\n mutating func deallocate() {\n guard let root = root?.takeRetainedValue() else { return }\n root.left.deallocate()\n root.right.deallocate()\n }\n}\n\nextension SlowUnmanagedSearchTree {\n func forEach(_ body: (Element) -> Void) {\n guard let root = root?.takeUnretainedValue() else { return }\n root.left.forEach(body)\n body(root.value)\n root.right.forEach(body)\n }\n\n func contains(_ value: Element) -> Bool {\n guard let root = root?.takeUnretainedValue() else { return false }\n if value == root.value { return true }\n return value < root.value\n ? root.left.contains(value)\n : root.right.contains(value)\n }\n\n mutating func insert(_ value: __owned Element) {\n guard let root = root?.takeUnretainedValue() else {\n self.root = Unmanaged.passRetained(Node(value: value))\n return\n }\n if value == root.value {\n return\n } else if value < root.value {\n root.left.insert(value)\n } else {\n root.right.insert(value)\n }\n }\n}\n\nstruct FastUnmanagedSearchTree<Element: Comparable> {\n class Node {\n var value: Element\n var left: FastUnmanagedSearchTree\n var right: FastUnmanagedSearchTree\n\n init(\n value: Element,\n left: FastUnmanagedSearchTree = .empty,\n right: FastUnmanagedSearchTree = .empty\n ) {\n self.left = left\n self.right = right\n self.value = value\n }\n }\n\n static var empty: FastUnmanagedSearchTree<Element> { FastUnmanagedSearchTree() }\n\n var root: Unmanaged<Node>?\n\n init() {\n self.root = nil\n }\n\n init(_root: Unmanaged<Node>?) {\n self.root = _root\n }\n}\n\nextension FastUnmanagedSearchTree {\n mutating func deallocate() {\n guard let root = root else { return }\n root._withUnsafeGuaranteedRef { root in\n root.left.deallocate()\n root.right.deallocate()\n }\n root.release()\n }\n}\n\nextension FastUnmanagedSearchTree {\n func forEach(_ body: (Element) -> Void) {\n guard let root = root else { return }\n root._withUnsafeGuaranteedRef { root in\n root.left.forEach(body)\n body(root.value)\n root.right.forEach(body)\n }\n }\n\n func contains(_ value: Element) -> Bool {\n guard let root = root else { return false }\n return root._withUnsafeGuaranteedRef { root in\n if value == root.value { return true }\n return value < root.value\n ? root.left.contains(value)\n : root.right.contains(value)\n }\n }\n\n mutating func insert(_ value: __owned Element) {\n guard let root = root else {\n self.root = Unmanaged.passRetained(Node(value: value))\n return\n }\n root._withUnsafeGuaranteedRef { root in\n if value == root.value {\n return\n } else if value < root.value {\n root.left.insert(value)\n } else {\n root.right.insert(value)\n }\n }\n }\n}\n\nstruct PointerSearchTree<Element: Comparable> {\n struct Node {\n var value: Element\n var left: PointerSearchTree = .empty\n var right: PointerSearchTree = .empty\n }\n\n static var empty: PointerSearchTree<Element> { PointerSearchTree() }\n\n var root: UnsafeMutablePointer<Node>?\n\n init() {\n self.root = nil\n }\n\n init(_root: UnsafeMutablePointer<Node>?) {\n self.root = _root\n }\n}\n\nextension PointerSearchTree {\n mutating func deallocate() {\n guard let root = root else { return }\n root.pointee.left.deallocate()\n root.pointee.right.deallocate()\n root.deallocate()\n }\n}\n\nextension PointerSearchTree {\n func forEach(_ body: (Element) -> Void) {\n guard let root = root else { return }\n root.pointee.left.forEach(body)\n body(root.pointee.value)\n root.pointee.right.forEach(body)\n }\n\n func contains(_ value: Element) -> Bool {\n guard let root = root else { return false }\n if value == root.pointee.value { return true }\n if value < root.pointee.value { return root.pointee.left.contains(value) }\n return root.pointee.right.contains(value)\n }\n\n mutating func insert(_ value: __owned Element) {\n guard let root = root else {\n let node = UnsafeMutablePointer<Node>.allocate(capacity: 1)\n node.initialize(to: Node(value: value))\n self.root = node\n return\n }\n if value == root.pointee.value {\n return\n } else if value < root.pointee.value {\n root.pointee.left.insert(value)\n } else {\n root.pointee.right.insert(value)\n }\n }\n}\n\n\n\nfunc run_ADT_insert(_ iterations: Int) {\n for _ in 0 ..< iterations {\n var tree = identity(EnumSearchTree<Int>.empty)\n for value in input {\n tree = tree.inserting(value)\n }\n blackHole(tree)\n }\n}\n\nfunc run_SlowUnmanaged_insert(_ iterations: Int) {\n for _ in 0 ..< iterations {\n var tree = identity(SlowUnmanagedSearchTree<Int>.empty)\n for value in input {\n tree.insert(value)\n }\n blackHole(tree)\n tree.deallocate()\n }\n}\n\nfunc run_FastUnmanaged_insert(_ iterations: Int) {\n for _ in 0 ..< iterations {\n var tree = identity(FastUnmanagedSearchTree<Int>.empty)\n for value in input {\n tree.insert(value)\n }\n blackHole(tree)\n tree.deallocate()\n }\n}\n\nfunc run_UnsafePointer_insert(_ iterations: Int) {\n for _ in 0 ..< iterations {\n var tree = identity(PointerSearchTree<Int>.empty)\n for value in input {\n tree.insert(value)\n }\n blackHole(tree)\n tree.deallocate()\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RandomTree.swift | cpp_apple_swift_benchmark_single-source_RandomTree.swift | Swift | 8,502 | 0.95 | 0.082353 | 0.043919 | python-kit | 271 | 2023-09-11T11:47:05.273368 | MIT | false | 0bca764e59b49433dc505d8c865f0044 |
//===--- RandomValues.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n//\n// Benchmark generating lots of random values. Measures the performance of\n// the default random generator and the algorithms for generating integers\n// and floating-point values.\n//\n\npublic let benchmarks = [\n BenchmarkInfo(name: "RandomIntegersDef", runFunction: run_RandomIntegersDef,\n tags: [.api], legacyFactor: 100),\n BenchmarkInfo(name: "RandomIntegersLCG", runFunction: run_RandomIntegersLCG,\n tags: [.api]),\n BenchmarkInfo(name: "RandomInt8Def", runFunction: run_RandomInt8Def,\n tags: [.api], legacyFactor: 100),\n BenchmarkInfo(name: "RandomInt8LCG", runFunction: run_RandomInt8LCG,\n tags: [.api]),\n BenchmarkInfo(name: "RandomInt64Def", runFunction: run_RandomInt64Def,\n tags: [.api], legacyFactor: 100),\n BenchmarkInfo(name: "RandomInt64LCG", runFunction: run_RandomInt64LCG,\n tags: [.api]),\n BenchmarkInfo(name: "RandomDoubleDef", runFunction: run_RandomDoubleDef,\n tags: [.api], legacyFactor: 100),\n BenchmarkInfo(name: "RandomDoubleLCG", runFunction: run_RandomDoubleLCG,\n tags: [.api]),\n BenchmarkInfo(name: "RandomDoubleOpaqueDef", runFunction: run_RandomDoubleOpaqueDef,\n tags: [.api], legacyFactor: 100),\n BenchmarkInfo(name: "RandomDoubleOpaqueLCG", runFunction: run_RandomDoubleOpaqueLCG,\n tags: [.api]),\n BenchmarkInfo(name: "RandomDouble01Def", runFunction: run_RandomDouble01Def,\n tags: [.api], legacyFactor: 100),\n BenchmarkInfo(name: "RandomDouble01LCG", runFunction: run_RandomDouble01LCG,\n tags: [.api]),\n]\n\n/// A linear congruential PRNG.\nstruct LCRNG: RandomNumberGenerator {\n private var state: UInt64\n\n init(seed: Int) {\n state = UInt64(truncatingIfNeeded: seed)\n for _ in 0..<10 { _ = next() }\n }\n\n mutating func next() -> UInt64 {\n state = 2862933555777941757 &* state &+ 3037000493\n return state\n }\n}\n\n@inline(never)\npublic func run_RandomIntegersDef(_ n: Int) {\n for _ in 0 ..< n {\n var x = 0\n for _ in 0 ..< 1_000 {\n x &+= .random(in: 0...10_000)\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomIntegersLCG(_ n: Int) {\n for _ in 0 ..< n {\n var x = 0\n var generator = LCRNG(seed: 0)\n for _ in 0 ..< 100_000 {\n x &+= .random(in: 0 ... 10_000, using: &generator)\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomInt8Def(_ n: Int) {\n for _ in 0 ..< n {\n var x: Int8 = 0\n for _ in 0 ..< 1_000 {\n x &+= .random(in: -65 ... identity(65))\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomInt8LCG(_ n: Int) {\n for _ in 0 ..< n {\n var x: Int8 = 0\n var generator = LCRNG(seed: 0)\n for _ in 0 ..< 100_000 {\n x &+= .random(in: -65 ... identity(65), using: &generator)\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomInt64Def(_ n: Int) {\n for _ in 0 ..< n {\n var x: Int64 = 0\n for _ in 0 ..< 1_000 {\n x &+= .random(in:\n -5_000_000_000_000_000_000 ... identity(5_000_000_000_000_000_000)\n )\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomInt64LCG(_ n: Int) {\n for _ in 0 ..< n {\n var x: Int64 = 0\n var generator = LCRNG(seed: 0)\n for _ in 0 ..< 100_000 {\n x &+= .random(in:\n -5_000_000_000_000_000_000 ... identity(5_000_000_000_000_000_000),\n using: &generator\n )\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomDoubleDef(_ n: Int) {\n for _ in 0 ..< n {\n var x = 0.0\n for _ in 0 ..< 1_000 {\n x += .random(in: -1000 ... 1000)\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomDoubleLCG(_ n: Int) {\n for _ in 0 ..< n {\n var x = 0.0\n var generator = LCRNG(seed: 0)\n for _ in 0 ..< 100_000 {\n x += .random(in: -1000 ... 1000, using: &generator)\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomDoubleOpaqueDef(_ n: Int) {\n for _ in 0 ..< n {\n var x = 0.0\n for _ in 0 ..< 1_000 {\n x += .random(in: -1000 ... identity(1000))\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomDoubleOpaqueLCG(_ n: Int) {\n for _ in 0 ..< n {\n var x = 0.0\n var generator = LCRNG(seed: 0)\n for _ in 0 ..< 100_000 {\n x += .random(in: -1000 ... identity(1000), using: &generator)\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomDouble01Def(_ n: Int) {\n for _ in 0 ..< n {\n var x = 0.0\n for _ in 0 ..< 1_000 {\n x += .random(in: 0 ..< 1)\n }\n blackHole(x)\n }\n}\n\n@inline(never)\npublic func run_RandomDouble01LCG(_ n: Int) {\n for _ in 0 ..< n {\n var x = 0.0\n var generator = LCRNG(seed: 0)\n for _ in 0 ..< 100_000 {\n x += .random(in: 0 ..< 1, using: &generator)\n }\n blackHole(x)\n }\n}\n \n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RandomValues.swift | cpp_apple_swift_benchmark_single-source_RandomValues.swift | Swift | 5,165 | 0.95 | 0.136585 | 0.091398 | awesome-app | 38 | 2023-10-19T06:56:14.001151 | GPL-3.0 | false | f83cb55a904bc4e232b78f67926d1a26 |
//===--- RangeAssignment.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "RangeAssignment",\n runFunction: run_RangeAssignment,\n tags: [.validation, .api])\n\n@inline(never)\npublic func run_RangeAssignment(_ scale: Int) {\n let range: Range = 100..<200\n var vector = [Double](repeating: 0.0 , count: 5000)\n let alfa = 1.0\n let n = 500*scale\n for _ in 1...n {\n vector[range] = ArraySlice(vector[range].map { $0 + alfa })\n }\n\n check(vector[100] == Double(n))\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RangeAssignment.swift | cpp_apple_swift_benchmark_single-source_RangeAssignment.swift | Swift | 990 | 0.95 | 0.09375 | 0.392857 | vue-tools | 449 | 2025-02-28T08:42:12.662802 | MIT | false | f8bbfe0db505ed8ca1f1071b09e5b37d |
//===--- RangeContains.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2024 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "RangeContainsRange",\n runFunction: run_RangeContainsRange,\n tags: [.validation, .api],\n setUpFunction: buildRanges),\n BenchmarkInfo(\n name: "RangeContainsClosedRange",\n runFunction: run_RangeContainsClosedRange,\n tags: [.validation, .api],\n setUpFunction: buildRanges),\n BenchmarkInfo(\n name: "ClosedRangeContainsRange",\n runFunction: run_ClosedRangeContainsRange,\n tags: [.validation, .api],\n setUpFunction: buildRanges),\n BenchmarkInfo(\n name: "ClosedRangeContainsClosedRange",\n runFunction: run_ClosedRangeContainsClosedRange,\n tags: [.validation, .api],\n setUpFunction: buildRanges),\n]\n\nprivate func buildRanges() {\n blackHole(ranges)\n blackHole(closedRanges)\n}\n\nprivate let ranges: [Range<Int>] = (-8...8).flatMap { a in (0...16).map { l in a..<(a+l) } }\nprivate let closedRanges: [ClosedRange<Int>] = (-8...8).flatMap { a in (0...16).map { l in a...(a+l) } }\n\n@inline(never)\npublic func run_RangeContainsRange(_ n: Int) {\n var checksum: UInt64 = 0\n for _ in 0..<n {\n for lhs in ranges {\n for rhs in ranges {\n if lhs.contains(rhs) { checksum += 1 }\n }\n }\n }\n check(checksum == 15725 * UInt64(n))\n}\n\n@inline(never)\npublic func run_RangeContainsClosedRange(_ n: Int) {\n var checksum: UInt64 = 0\n for _ in 0..<n {\n for lhs in ranges {\n for rhs in closedRanges {\n if lhs.contains(rhs) { checksum += 1 }\n }\n }\n }\n check(checksum == 10812 * UInt64(n))\n}\n\n@inline(never)\npublic func run_ClosedRangeContainsRange(_ n: Int) {\n var checksum: UInt64 = 0\n for _ in 0..<n {\n for lhs in closedRanges {\n for rhs in ranges {\n if lhs.contains(rhs) { checksum += 1 }\n }\n }\n }\n check(checksum == 17493 * UInt64(n))\n}\n\n@inline(never)\npublic func run_ClosedRangeContainsClosedRange(_ n: Int) {\n var checksum: UInt64 = 0\n for _ in 0..<n {\n for lhs in closedRanges {\n for rhs in closedRanges {\n if lhs.contains(rhs) { checksum += 1 }\n }\n }\n }\n check(checksum == 12597 * UInt64(n))\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RangeContains.swift | cpp_apple_swift_benchmark_single-source_RangeContains.swift | Swift | 2,609 | 0.95 | 0.1875 | 0.125 | python-kit | 400 | 2024-03-22T18:08:01.193814 | BSD-3-Clause | false | a077ec6ba9634cf1972fef640d60f3a0 |
//===--- RangeAssignment.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n#if swift(>=4.2)\npublic let benchmarks = [\n BenchmarkInfo(\n name: "RangeIterationSigned",\n runFunction: run_RangeIterationSigned,\n tags: [.validation, .api]\n ),\n BenchmarkInfo(\n name: "RangeIterationSigned64",\n runFunction: run_RangeIterationSigned64,\n tags: [.validation, .api]\n ),\n BenchmarkInfo(\n name: "RangeIterationUnsigned",\n runFunction: run_RangeIterationUnsigned,\n tags: [.validation, .api]\n ),\n]\n#else\npublic let benchmarks = [\n BenchmarkInfo(\n name: "RangeIterationSigned",\n runFunction: run_RangeIterationSigned,\n tags: [.validation, .api]\n )\n]\n#endif\n\n@inline(never)\nfunc sum(_ x: UInt64, _ y: UInt64) -> UInt64 {\n return x &+ y\n}\n\n@inline(never)\npublic func run_RangeIterationSigned(_ n: Int) {\n let range = 0..<100000\n var checksum: UInt64 = 0\n for _ in 1...n {\n for e in range {\n checksum = sum(checksum, UInt64(e))\n }\n }\n\n check(checksum == 4999950000 * UInt64(n))\n}\n\n#if swift(>=4.2)\n\n@inline(never)\npublic func run_RangeIterationSigned64(_ n: Int) {\n let range: Range<Int64> = 0..<100000\n var check: UInt64 = 0\n for _ in 1...n {\n for e in range {\n check = sum(check, UInt64(e))\n }\n }\n\n check(check == 4999950000 * UInt64(n))\n}\n\n@inline(never)\npublic func run_RangeIterationUnsigned(_ n: Int) {\n let range: Range<UInt> = 0..<100000\n var check: UInt64 = 0\n for _ in 1...n {\n for e in range {\n check = sum(check, UInt64(e))\n }\n }\n\n check(check == 4999950000 * UInt64(n))\n}\n\n#endif\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RangeIteration.swift | cpp_apple_swift_benchmark_single-source_RangeIteration.swift | Swift | 2,030 | 0.95 | 0.11236 | 0.205128 | node-utils | 294 | 2025-06-23T11:35:59.622358 | GPL-3.0 | false | 883305fbe3515bed23b11a18da7f9ae3 |
//===--- RangeOverlaps.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "RangeOverlapsRange",\n runFunction: run_RangeOverlapsRange,\n tags: [.validation, .api],\n setUpFunction: buildRanges),\n BenchmarkInfo(\n name: "RangeOverlapsClosedRange",\n runFunction: run_RangeOverlapsClosedRange,\n tags: [.validation, .api],\n setUpFunction: buildRanges),\n BenchmarkInfo(\n name: "ClosedRangeOverlapsClosedRange",\n runFunction: run_ClosedRangeOverlapsClosedRange,\n tags: [.validation, .api],\n setUpFunction: buildRanges)\n]\n\nprivate func buildRanges() {\n blackHole(ranges)\n blackHole(closedRanges)\n}\n\nprivate let ranges: [Range<Int>] = (-8...8).flatMap { a in (0...16).map { l in a..<(a+l) } }\nprivate let closedRanges: [ClosedRange<Int>] = (-8...8).flatMap { a in (0...16).map { l in a...(a+l) } }\n\n@inline(never)\npublic func run_RangeOverlapsRange(_ n: Int) {\n var checksum: UInt64 = 0\n for _ in 0..<n {\n for lhs in ranges {\n for rhs in ranges {\n if lhs.overlaps(rhs) { checksum += 1 }\n }\n }\n }\n check(checksum == 47872 * UInt64(n))\n}\n\n@inline(never)\npublic func run_RangeOverlapsClosedRange(_ n: Int) {\n var checksum: UInt64 = 0\n for _ in 0..<n {\n for lhs in ranges {\n for rhs in closedRanges {\n if lhs.overlaps(rhs) { checksum += 1 }\n }\n }\n }\n check(checksum == 51680 * UInt64(n))\n}\n\n@inline(never)\npublic func run_ClosedRangeOverlapsClosedRange(_ n: Int) {\n var checksum: UInt64 = 0\n for _ in 0..<n {\n for lhs in closedRanges {\n for rhs in closedRanges {\n if lhs.overlaps(rhs) { checksum += 1 }\n }\n }\n }\n check(checksum == 55777 * UInt64(n))\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RangeOverlaps.swift | cpp_apple_swift_benchmark_single-source_RangeOverlaps.swift | Swift | 2,172 | 0.95 | 0.179487 | 0.15493 | awesome-app | 74 | 2024-08-27T22:58:57.294820 | MIT | false | cb817f0def061fb5cb4b46c17d69cb1f |
// RangeReplaceablePlusDefault benchmark\n//\n// Source: https://gist.github.com/airspeedswift/392599e7eeeb74b481a7\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "RangeReplaceableCollectionPlusDefault",\n runFunction: run_RangeReplaceableCollectionPlusDefault,\n tags: [.validation],\n legacyFactor: 4\n )\n\n@inline(never)\npublic func run_RangeReplaceableCollectionPlusDefault(_ n: Int) {\n let stringsRef = [1, 2, 3]\n let strings = ["1", "2", "3"]\n let toInt = { (s: String) -> Int? in Int(s) }\n var a = [Int]()\n var b = [Int]()\n\n for _ in 1...250*n {\n let a2: Array = mapSome(strings, toInt)\n let b2 = mapSome(strings, toInt)\n a = a2\n b = b2\n\n if !compareRef(a, b, stringsRef) {\n break\n }\n }\n\n check(compareRef(a, b, stringsRef))\n}\n\nfunc compareRef(_ a: [Int], _ b: [Int], _ ref: [Int]) -> Bool {\n return ref == a && ref == b\n}\n\n// This algorithm returns a generic placeholder\n// that can be any kind of range-replaceable collection:\nfunc mapSome\n<S: Sequence, C: RangeReplaceableCollection>\n(_ source: S, _ transform: (S.Element)->C.Element?) -> C {\n var result = C()\n for x in source {\n if let y = transform(x) {\n result.append(y)\n }\n }\n return result\n}\n\n// If you write a second version that returns an array,\n// you can call the more general version for implementation:\nfunc mapSome<S: Sequence,U>(_ source: S, _ transform: (S.Element)->U?)->[U] {\n // just calls the more generalized version\n // (works because here, the return type\n // is now of a specific type, an Array)\n return mapSome(source, transform)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RangeReplaceableCollectionPlusDefault.swift | cpp_apple_swift_benchmark_single-source_RangeReplaceableCollectionPlusDefault.swift | Swift | 1,595 | 0.95 | 0.080645 | 0.188679 | awesome-app | 457 | 2024-06-11T04:50:22.637043 | BSD-3-Clause | false | dda1c5872b69673656e65e970574b1e8 |
//===--- RC4.swift --------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test is based on util/benchmarks/RC4, with modifications\n// for performance measuring.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "RC4",\n runFunction: run_RC4,\n tags: [.validation, .algorithm])\n\nstruct RC4 {\n var state: [UInt8]\n var i: UInt8 = 0\n var j: UInt8 = 0\n\n init() {\n state = [UInt8](repeating: 0, count: 256)\n }\n\n mutating\n func initialize(_ key: [UInt8]) {\n for i in 0..<256 {\n state[i] = UInt8(i)\n }\n\n var j: UInt8 = 0\n for i in 0..<256 {\n let k: UInt8 = key[i % key.count]\n let s: UInt8 = state[i]\n j = j &+ s &+ k\n swapByIndex(i, y: Int(j))\n }\n }\n\n mutating\n func swapByIndex(_ x: Int, y: Int) {\n let t1: UInt8 = state[x]\n let t2: UInt8 = state[y]\n state[x] = t2\n state[y] = t1\n }\n\n mutating\n func next() -> UInt8 {\n i = i &+ 1\n j = j &+ state[Int(i)]\n swapByIndex(Int(i), y: Int(j))\n return state[Int(state[Int(i)] &+ state[Int(j)]) & 0xFF]\n }\n\n mutating\n func encrypt(_ data: inout [UInt8]) {\n let cnt = data.count\n for i in 0..<cnt {\n data[i] = data[i] ^ next()\n }\n }\n}\n\nlet refResults: [UInt8] = [\n 245, 62, 245, 202, 138, 120, 186, 107, 255, 189,\n 184, 223, 65, 77, 112, 201, 238, 161, 74, 192, 145,\n 21, 43, 41, 91, 136, 182, 176, 237, 155, 208, 16,\n 17, 139, 33, 195, 24, 136, 79, 183, 211, 21, 56,\n 202, 235, 65, 201, 184, 68, 29, 110, 218, 112, 122,\n 194, 77, 41, 230, 147, 84, 0, 233, 168, 6, 55, 131,\n 70, 119, 41, 119, 234, 131, 87, 24, 51, 130, 28,\n 66, 172, 105, 33, 97, 179, 48, 81, 229, 114, 216,\n 208, 119, 39, 31, 47, 109, 172, 215, 246, 210, 48,\n 203]\n\n\n@inline(never)\npublic func run_RC4(_ n: Int) {\n let messageLen = 100\n let iterations = 500\n let secret = "This is my secret message"\n let key = "This is my key"\n let secretData : [UInt8] = Array(secret.utf8)\n let keyData : [UInt8] = Array(key.utf8)\n\n var longData : [UInt8] = [UInt8](repeating: 0, count: messageLen)\n\n for _ in 1...n {\n // Generate a long message.\n for i in 0..<messageLen {\n longData[i] = secretData[i % secretData.count]\n }\n\n var enc = RC4()\n enc.initialize(keyData)\n\n for _ in 1...iterations {\n enc.encrypt(&longData)\n }\n\n check(longData == refResults)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RC4.swift | cpp_apple_swift_benchmark_single-source_RC4.swift | Swift | 2,782 | 0.95 | 0.081081 | 0.148936 | react-lib | 240 | 2024-07-02T06:47:56.130165 | Apache-2.0 | false | 5be3f8c17c548631e9f781dd64463524 |
//===--- RecursiveOwnedParameter.swift ------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "RecursiveOwnedParameter",\n runFunction: run_RecursiveOwnedParameter,\n tags: [.validation, .api, .Array, .refcount])\n\n// This test recursively visits each element of an array in a class and compares\n// it with every value in a different array stored in a different class. The\n// idea is to make sure that we can get rid of the overhead from guaranteed\n// parameters.\n\n// We use final since we are not interesting in devirtualization for the\n// purposes of this test.\nfinal\nclass ArrayWrapper {\n var data: [Int]\n\n init(_ count: Int, _ initialValue: Int) {\n data = [Int](repeating: initialValue, count: count)\n }\n\n func compare(_ b: ArrayWrapper, _ iteration: Int, _ stopIteration: Int) -> Bool {\n // We will never return true here by design. We want to test the full effect\n // every time of retaining, releasing.\n if iteration == stopIteration || data[iteration] == b.data[iteration] {\n return true\n }\n\n return compare(b, iteration &+ 1, stopIteration)\n }\n}\n\n@inline(never)\npublic func run_RecursiveOwnedParameter(_ n: Int) {\n let numElts = 1_000\n\n let a = ArrayWrapper(numElts, 0)\n let b = ArrayWrapper(numElts, 1)\n\n var result = 0\n for _ in 0..<100*n {\n if a.compare(b, 0, numElts) {\n result += 1\n }\n }\n let refResult = 100*n\n check(result == refResult)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RecursiveOwnedParameter.swift | cpp_apple_swift_benchmark_single-source_RecursiveOwnedParameter.swift | Swift | 1,901 | 0.95 | 0.145161 | 0.365385 | vue-tools | 579 | 2023-09-27T02:39:18.351606 | MIT | false | 4660bdf48a37ff4f0bcafc5224c67d70 |
//===--- ReduceInto.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "FilterEvenUsingReduce", runFunction: run_FilterEvenUsingReduce, tags: [.validation, .api], legacyFactor: 10),\n BenchmarkInfo(name: "FilterEvenUsingReduceInto", runFunction: run_FilterEvenUsingReduceInto, tags: [.validation, .api]),\n BenchmarkInfo(name: "FrequenciesUsingReduce", runFunction: run_FrequenciesUsingReduce, tags: [.validation, .api], legacyFactor: 10),\n BenchmarkInfo(name: "FrequenciesUsingReduceInto", runFunction: run_FrequenciesUsingReduceInto, tags: [.validation, .api], legacyFactor: 10),\n BenchmarkInfo(name: "SumUsingReduce", runFunction: run_SumUsingReduce, tags: [.validation, .api]),\n BenchmarkInfo(name: "SumUsingReduceInto", runFunction: run_SumUsingReduceInto, tags: [.validation, .api]),\n]\n\n// Sum\n\n@inline(never)\npublic func run_SumUsingReduce(_ n: Int) {\n let numbers = [Int](0..<1000)\n\n var c = 0\n for _ in 1...n*1000 {\n c = c &+ numbers.reduce(0) { (acc: Int, num: Int) -> Int in\n acc &+ num\n }\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_SumUsingReduceInto(_ n: Int) {\n let numbers = [Int](0..<1000)\n\n var c = 0\n for _ in 1...n*1000 {\n c = c &+ numbers.reduce(into: 0) { (acc: inout Int, num: Int) in\n acc = acc &+ num\n }\n }\n check(c != 0)\n}\n\n// Filter\n\n@inline(never)\npublic func run_FilterEvenUsingReduce(_ n: Int) {\n let numbers = [Int](0..<100)\n\n var c = 0\n for _ in 1...n*10 {\n let a = numbers.reduce([]) { (acc: [Int], num: Int) -> [Int] in\n var a = acc\n if num % 2 == 0 {\n a.append(num)\n }\n return a\n }\n c = c &+ a.count\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_FilterEvenUsingReduceInto(_ n: Int) {\n let numbers = [Int](0..<100)\n\n var c = 0\n for _ in 1...n*100 {\n let a = numbers.reduce(into: []) { (acc: inout [Int], num: Int) in\n if num % 2 == 0 {\n acc.append(num)\n }\n }\n c = c &+ a.count\n }\n check(c != 0)\n}\n\n// Frequencies\n\n@inline(never)\npublic func run_FrequenciesUsingReduce(_ n: Int) {\n let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789"\n\n var c = 0\n for _ in 1...n*10 {\n let a = s.reduce([:]) {\n (acc: [Character: Int], c: Character) -> [Character: Int] in\n var d = acc\n d[c, default: 0] += 1\n return d\n }\n c = c &+ a.count\n }\n check(c != 0)\n}\n\n@inline(never)\npublic func run_FrequenciesUsingReduceInto(_ n: Int) {\n let s = "thequickbrownfoxjumpsoverthelazydogusingasmanycharacteraspossible123456789"\n\n var c = 0\n for _ in 1...n*10 {\n let a = s.reduce(into: [:]) {\n (acc: inout [Character: Int], c: Character) in\n acc[c, default: 0] += 1\n }\n c = c &+ a.count\n }\n check(c != 0)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ReduceInto.swift | cpp_apple_swift_benchmark_single-source_ReduceInto.swift | Swift | 3,237 | 0.95 | 0.083333 | 0.135922 | react-lib | 808 | 2023-09-18T11:15:55.781730 | BSD-3-Clause | false | ab25793ad71c4a998e80ee374bebc30b |
//===--- RemoveWhere.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n // tests repeated remove(at:) calls in generic code\n BenchmarkInfo(name: "RemoveWhereQuadraticStrings", runFunction: run_RemoveWhereQuadraticStrings, tags: [.validation, .api], setUpFunction: buildWorkload),\n BenchmarkInfo(name: "RemoveWhereQuadraticInts", runFunction: run_RemoveWhereQuadraticInts, tags: [.validation, .api], setUpFunction: buildWorkload),\n // tests performance of RangeReplaceableCollection.filter\n BenchmarkInfo(name: "RemoveWhereFilterStrings", runFunction: run_RemoveWhereFilterStrings, tags: [.validation, .api], setUpFunction: buildWorkload),\n BenchmarkInfo(name: "RemoveWhereFilterInts", runFunction: run_RemoveWhereFilterInts, tags: [.validation, .api], setUpFunction: buildWorkload),\n // these two variants test the impact of reference counting and\n // swapping/moving\n BenchmarkInfo(name: "RemoveWhereMoveStrings", runFunction: run_RemoveWhereMoveStrings, tags: [.validation, .api], setUpFunction: buildWorkload),\n BenchmarkInfo(name: "RemoveWhereMoveInts", runFunction: run_RemoveWhereMoveInts, tags: [.validation, .api], setUpFunction: buildWorkload),\n BenchmarkInfo(name: "RemoveWhereSwapStrings", runFunction: run_RemoveWhereSwapStrings, tags: [.validation, .api], setUpFunction: buildWorkload),\n BenchmarkInfo(name: "RemoveWhereSwapInts", runFunction: run_RemoveWhereSwapInts, tags: [.validation, .api], setUpFunction: buildWorkload),\n // these test performance of filter, character iteration/comparison \n BenchmarkInfo(name: "RemoveWhereFilterString", runFunction: run_RemoveWhereFilterString, tags: [.validation, .api], setUpFunction: buildWorkload),\n BenchmarkInfo(name: "RemoveWhereQuadraticString", runFunction: run_RemoveWhereQuadraticString, tags: [.validation, .api], setUpFunction: buildWorkload),\n]\n\nextension RangeReplaceableCollection {\n mutating func removeWhere_quadratic(where match: (Element) throws -> Bool) rethrows {\n for i in indices.reversed() {\n if try match(self[i]) {\n remove(at: i)\n }\n }\n }\n\n mutating func removeWhere_filter(where match: (Element) throws -> Bool) rethrows {\n try self = self.filter { try !match($0) }\n }\n}\n\nextension RangeReplaceableCollection where Self: MutableCollection {\n mutating func removeWhere_move(where match: (Element) throws -> Bool) rethrows {\n guard var i = try firstIndex(where: match) else { return }\n\n var j = index(after: i)\n while j != endIndex {\n let element = self[j]\n if try !match(element) {\n self[i] = element\n formIndex(after: &i)\n }\n formIndex(after: &j)\n }\n\n removeSubrange(i...)\n }\n\n mutating func removeWhere_swap(where match: (Element) throws -> Bool) rethrows {\n guard var i = try firstIndex(where: match) else { return }\n\n var j = index(after: i)\n while j != endIndex {\n if try !match(self[i]) {\n self.swapAt(i,j)\n formIndex(after: &i)\n }\n formIndex(after: &j)\n }\n\n removeSubrange(i...)\n }\n}\n\nfunc testQuadratic<C: RangeReplaceableCollection>(workload: inout C) {\n var i = 0\n workload.removeWhere_quadratic { _ in\n i = i &+ 1\n return i%8 == 0\n }\n}\n\nfunc testFilter<C: RangeReplaceableCollection>(workload: inout C) {\n var i = 0\n workload.removeWhere_filter { _ in\n i = i &+ 1\n return i%8 == 0\n }\n}\n\nfunc testMove<C: RangeReplaceableCollection & MutableCollection>(workload: inout C) {\n var i = 0\n workload.removeWhere_move { _ in\n i = i &+ 1\n return i%8 == 0\n }\n}\n\nfunc testSwap<C: RangeReplaceableCollection & MutableCollection>(workload: inout C) {\n var i = 0\n workload.removeWhere_swap { _ in\n i = i &+ 1\n return i%8 == 0\n }\n}\n\nlet n = 10_000\nlet strings = (0..<n).map({ "\($0): A long enough string to defeat the SSO" })\nlet ints = Array(0..<n)\nlet str = String(repeating: "A very long ASCII string.", count: n/50)\n\nfunc buildWorkload() {\n blackHole(strings)\n blackHole(ints)\n blackHole(str)\n}\n\n\n@inline(never)\nfunc run_RemoveWhereQuadraticStrings(_ scale: Int) {\n for _ in 0..<scale {\n var workload = strings; workload.swapAt(0,1)\n testQuadratic(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereQuadraticInts(_ scale: Int) {\n for _ in 0..<scale {\n var workload = ints; workload.swapAt(0,1)\n testQuadratic(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereFilterStrings(_ scale: Int) {\n for _ in 0..<scale {\n var workload = strings; workload.swapAt(0,1)\n testFilter(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereFilterInts(_ scale: Int) {\n for _ in 0..<scale {\n var workload = ints; workload.swapAt(0,1)\n testFilter(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereMoveStrings(_ scale: Int) {\n for _ in 0..<scale {\n var workload = strings; workload.swapAt(0,1)\n testMove(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereMoveInts(_ scale: Int) {\n for _ in 0..<scale {\n var workload = ints; workload.swapAt(0,1)\n testMove(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereSwapStrings(_ scale: Int) {\n for _ in 0..<scale {\n var workload = strings; workload.swapAt(0,1)\n testSwap(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereSwapInts(_ scale: Int) {\n for _ in 0..<scale {\n var workload = ints; workload.swapAt(0,1)\n testSwap(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereFilterString(_ scale: Int) {\n for _ in 0..<scale {\n var workload = str\n workload.append("!")\n testFilter(workload: &workload)\n }\n}\n\n@inline(never)\nfunc run_RemoveWhereQuadraticString(_ scale: Int) {\n for _ in 0..<scale {\n var workload = str\n workload.append("!")\n testQuadratic(workload: &workload)\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RemoveWhere.swift | cpp_apple_swift_benchmark_single-source_RemoveWhere.swift | Swift | 6,231 | 0.95 | 0.121951 | 0.090395 | vue-tools | 548 | 2025-04-01T18:40:58.002101 | BSD-3-Clause | false | 08f51e1552adfbe002eb114fed202278 |
//===--- ReversedCollections.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "ReversedArray2", runFunction: run_ReversedArray, tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(arrayInput) },\n tearDownFunction: { arrayInput = nil }),\n BenchmarkInfo(name: "ReversedBidirectional", runFunction: run_ReversedBidirectional, tags: [.validation, .api, .cpubench]),\n BenchmarkInfo(name: "ReversedDictionary2", runFunction: run_ReversedDictionary, tags: [.validation, .api, .Dictionary],\n setUpFunction: { blackHole(dictionaryInput) },\n tearDownFunction: { dictionaryInput = nil })\n]\n\n// These benchmarks compare the performance of iteration through several\n// collection types after being reversed.\nlet length = 100_000\n\nvar arrayInput: [Int]! = Array(repeating: 1, count: length).reversed()\n\n@inline(never)\npublic func run_ReversedArray(_ n: Int) {\n let reversedArray: [Int] = arrayInput\n\n // Iterate over the underlying type\n // ReversedRandomAccessCollection<Array<Int>>\n for _ in 1...n {\n for item in reversedArray {\n blackHole(item)\n }\n }\n}\n\n@inline(never)\npublic func run_ReversedBidirectional(_ n: Int) {\n // Iterate over the underlying type\n // ReversedCollection<AnyBidirectionalCollection<Int>>\n for _ in 1...n {\n let bidirectional = AnyBidirectionalCollection(0..<length)\n let reversedBidirectional = bidirectional.reversed()\n for item in reversedBidirectional {\n blackHole(item)\n }\n }\n}\n\nvar dictionaryInput: [(Int, Int)]! = {\n var dictionary = [Int: Int]()\n for k in 0..<length {\n dictionary[k] = k\n }\n return dictionary.reversed()\n}()\n\n@inline(never)\npublic func run_ReversedDictionary(_ n: Int) {\n let reversedDictionary: [(Int, Int)] = dictionaryInput\n\n // Iterate over the underlying type\n // Array<(Int, Int)>\n for _ in 1...n {\n for (key, value) in reversedDictionary {\n blackHole(key)\n blackHole(value)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_ReversedCollections.swift | cpp_apple_swift_benchmark_single-source_ReversedCollections.swift | Swift | 2,433 | 0.95 | 0.116883 | 0.283582 | awesome-app | 837 | 2023-08-31T13:11:46.742428 | MIT | false | 428af83c8a44505d0bfe4a93045602e5 |
//===--- RGBHistogram.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// Performance benchmark for creating RGB histograms\n// rdar://problem/18539486\n//\n// Description:\n// Create a sorted sparse RGB histogram from an array of 300 RGB values.\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "RGBHistogram",\n runFunction: run_RGBHistogram,\n tags: [.validation, .algorithm],\n legacyFactor: 10),\n BenchmarkInfo(name: "RGBHistogramOfObjects",\n runFunction: run_RGBHistogramOfObjects,\n tags: [.validation, .algorithm],\n legacyFactor: 100),\n]\n\n@inline(never)\npublic func run_RGBHistogram(_ n: Int) {\n var histogram = [(key: rrggbb_t, value: Int)]()\n for _ in 1...10*n {\n histogram = createSortedSparseRGBHistogram(samples)\n if !isCorrectHistogram(histogram) {\n break\n }\n }\n check(isCorrectHistogram(histogram))\n}\n\ntypealias rrggbb_t = UInt32\n\nlet samples: [rrggbb_t] = [\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0x00FF0000, 0x00FF0000, 0x000000FF, 0x000000FF, 0x000000FF, 0x000000FF,\n 0x00000000, 0x00555555, 0x00AAAAAA, 0x00FFFFFF, 0x00AAAAAA, 0x00FFFFFF,\n 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080, 0x00808080,\n 0xCCD45FBC, 0xA56F39E4, 0x8C08DBA7, 0xDA4413D7, 0x43926C6B, 0x592975FE,\n 0xC77E47ED, 0xB28F427D, 0x90D7C464, 0x805A003A, 0xAB79B390, 0x49D859B3,\n 0x2419213A, 0x69E8C61D, 0xC4BE948F, 0x896CC6D0, 0xE4F3DFF1, 0x466B68FA,\n 0xC8084E2A, 0x3FC1F2C4, 0x0E0D47F4, 0xB268BFE6, 0x9F990E6A, 0x7389F2F8,\n 0x0720FD81, 0x65388005, 0xD8307612, 0xEC75B9B0, 0xB0C51360, 0x29647EB4,\n 0x6E8B02E6, 0xEFE9F0F4, 0xFEF0EB89, 0x41BBD587, 0xCD19E510, 0x6A710BBD,\n 0xFF146228, 0xFB34AD0C, 0x2AEB5588, 0x71993821, 0x9FC8CA5C, 0xF99E969B,\n 0x8DF78241, 0x21ADFB7C, 0x4DE5E465, 0x0C171D2F, 0x2C08CECF, 0x3318440A,\n 0xEC8F8D1C, 0x6CAFD68E, 0xCA35F571, 0x68A37E1A, 0x3047F87F, 0x50CC39DE,\n 0x776CF5CB, 0x75DC4595, 0x77E32288, 0x14899C0D, 0x14835CF6, 0x0A732F76,\n 0xA4B05790, 0x34CBED42, 0x5A6964CE, 0xEA4CA5F7, 0x3DECB0F1, 0x5015D419,\n 0x84EBC299, 0xC656B381, 0xFA2840C5, 0x618D754E, 0x003B8D96, 0xCE91AA8E,\n 0xBD9784DB, 0x9372E919, 0xC138BEA6, 0xF0B3E3AD, 0x4E4F60BF, 0xC1598ABE,\n 0x930873DB, 0x0F029E3A, 0xBEFC0125, 0x10645D6D, 0x1FF93547, 0xA7069CB5,\n 0xCF0B7E06, 0xE33EDC17, 0x8C5E1F48, 0x2FB345E1, 0x3B0070E0, 0x0421E568,\n 0xB39A42A0, 0xB935DA8B, 0x281C30F0, 0xB2E48677, 0x277A9A45, 0x52AF9FC6,\n 0xBBDF4048, 0xC668137A, 0xF39020D1, 0x71BEE810, 0x5F2B3825, 0x25C863FB,\n 0x876144E8, 0x9B4108C3, 0xF735CB08, 0x8B77DEEC, 0x0185A067, 0xB964F42B,\n 0xA2EC236B, 0x3C08646F, 0xB514C4BE, 0x37EE9689, 0xACF97317, 0x1EA4F7C6,\n 0x453A6F13, 0x01C25E42, 0xA052BB3B, 0x71A699CB, 0xC728AE88, 0x128A656F,\n 0x78F64E55, 0x045967E0, 0xC5DC4125, 0xDA39F6FE, 0x873785B9, 0xB6BB446A,\n 0xF4F5093F, 0xAF05A4EC, 0xB5DB854B, 0x7ADA6A37, 0x9EA218E3, 0xCCCC9316,\n 0x86A133F8, 0x8AF47795, 0xCBA235D4, 0xBB9101CC, 0xBCC8C8A3, 0x02BAC911,\n 0x45C17A8C, 0x896C81FC, 0x4974FA22, 0xEA7CD629, 0x103ED364, 0x4C644503,\n 0x607F4D9F, 0x9733E55E, 0xA360439D, 0x1DB568FD, 0xB7A5C3A1, 0xBE84492D\n]\n\nfunc isCorrectHistogram(_ histogram: [(key: rrggbb_t, value: Int)]) -> Bool {\n return histogram.count == 157 &&\n histogram[0].0 == 0x00808080 && histogram[0].1 == 54 &&\n histogram[156].0 == 0x003B8D96 && histogram[156].1 == 1\n}\n\nfunc createSortedSparseRGBHistogram<S : Sequence>(\n _ samples: S\n) -> [(key: rrggbb_t, value: Int)]\n where S.Element == rrggbb_t\n{\n var histogram = Dictionary<rrggbb_t, Int>()\n\n for sample in samples {\n let i = histogram.index(forKey: sample)\n histogram[sample] = ((i != nil) ? histogram[i!].1 : 0) + 1\n }\n\n return histogram.sorted() {\n if $0.1 == $1.1 {\n return $0.0 > $1.0\n } else {\n return $0.1 > $1.1\n }\n }\n}\n\nclass Box<T : Hashable> : Hashable {\n var value: T\n\n init(_ v: T) {\n value = v\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(value)\n }\n\n static func ==(lhs: Box, rhs: Box) -> Bool {\n return lhs.value == rhs.value\n }\n}\n\nfunc isCorrectHistogramOfObjects(_ histogram: [(key: Box<rrggbb_t>, value: Box<Int>)]) -> Bool {\n return histogram.count == 157 &&\n histogram[0].0.value == 0x00808080 && histogram[0].1.value == 54 &&\n histogram[156].0.value == 0x003B8D96 && histogram[156].1.value == 1\n}\n\nfunc createSortedSparseRGBHistogramOfObjects<S : Sequence>(\n _ samples: S\n) -> [(key: Box<rrggbb_t>, value: Box<Int>)]\n where S.Element == rrggbb_t\n{\n var histogram = Dictionary<Box<rrggbb_t>, Box<Int>>()\n\n for sample in samples {\n let boxedSample = Box(sample)\n let i = histogram.index(forKey: boxedSample)\n histogram[boxedSample] = Box(((i != nil) ? histogram[i!].1.value : 0) + 1)\n }\n\n return histogram.sorted() {\n if $0.1 == $1.1 {\n return $0.0.value > $1.0.value\n } else {\n return $0.1.value > $1.1.value\n }\n }\n}\n\n@inline(never)\npublic func run_RGBHistogramOfObjects(_ n: Int) {\n var histogram = [(key: Box<rrggbb_t>, value: Box<Int>)]()\n for _ in 1...n {\n histogram = createSortedSparseRGBHistogramOfObjects(samples)\n if !isCorrectHistogramOfObjects(histogram) {\n break\n }\n }\n check(isCorrectHistogramOfObjects(histogram))\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RGBHistogram.swift | cpp_apple_swift_benchmark_single-source_RGBHistogram.swift | Swift | 7,424 | 0.95 | 0.067039 | 0.099379 | awesome-app | 345 | 2024-09-03T07:39:26.265169 | Apache-2.0 | false | 5006ccfd08bf6f50bf58178f274882a6 |
//===--- RomanNumbers.swift -----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// Mini benchmark implementing roman numeral conversions to/from integers.\n// Measures performance of Substring.starts(with:), dropFirst and String.append\n// with very short string arguments.\n\nlet t: [BenchmarkCategory] = [.api, .String, .algorithm]\nlet n = 270\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "RomanNumbers2",\n runFunction: {\n checkId($0, upTo: n, { $0.romanNumeral }, Int.init(romanSSsWdF:)) },\n tags: t),\n]\n\n@inline(__always)\nfunc checkId(_ n: Int, upTo limit: Int, _ itor: (Int) -> String,\n _ rtoi: (String) -> Int?) {\n for _ in 1...n {\n check(\n zip(1...limit, (1...limit).map(itor).map(rtoi)).allSatisfy { $0 == $1 })\n }\n}\n\nlet romanTable: KeyValuePairs<String, Int> = [\n "M": 1000, "CM": 900, "D": 500, "CD": 400,\n "C": 100_, "XC": 90_, "L": 50_, "XL": 40_,\n "X": 10__, "IX": 9__, "V": 5__, "IV": 4__,\n "I": 1,\n]\n\nextension BinaryInteger {\n // Imperative Style\n // See https://www.rosettacode.org/wiki/Roman_numerals/Encode#Swift\n // See https://www.rosettacode.org/wiki/Roman_numerals/Decode#Swift\n\n var romanNumeral: String {\n var result = ""\n var n = self\n for (numeral, value) in romanTable {\n while n >= value {\n result += numeral\n n -= Self(value)\n }\n }\n return result\n }\n\n init?(romanSSsWdF number: String) {\n self = 0\n var raw = Substring(number)\n for (numeral, value) in romanTable {\n while raw.starts(with: numeral) {\n self += Self(value)\n raw = raw.dropFirst(numeral.count)\n }\n }\n guard raw.isEmpty else { return nil }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_RomanNumbers.swift | cpp_apple_swift_benchmark_single-source_RomanNumbers.swift | Swift | 2,111 | 0.95 | 0.094595 | 0.261538 | awesome-app | 889 | 2025-04-10T21:11:11.988266 | BSD-3-Clause | false | f4dfce3f1eafb771e72b9e4da71fe672 |
//===--- SequenceAlgos.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n\nimport TestsUtils\n\n// This benchmark tests closureless versions of min and max, both contains,\n// repeatElement and reduce, on a number of different sequence types.\n// To avoid too many little micro benchmarks, it measures them all together\n// for each sequence type.\n\nlet t: [BenchmarkCategory] = [.validation, .api]\n\npublic let benchmarks = [\n BenchmarkInfo(name: "SequenceAlgosList", runFunction: { for _ in 0..<$0 {\n benchmarkSequenceAlgos(s: l, n: n)\n benchmarkEquatableSequenceAlgos(s: l, n: n)\n }}, tags: t, setUpFunction: { blackHole(l) }, legacyFactor: 10),\n BenchmarkInfo(name: "SequenceAlgosArray", runFunction: { for _ in 0..<$0 {\n benchmarkSequenceAlgos(s: a, n: a.count)\n benchmarkEquatableSequenceAlgos(s: a, n: a.count)\n }}, tags: t, setUpFunction: { blackHole(a) }, legacyFactor: 10),\n BenchmarkInfo(name: "SequenceAlgosContiguousArray",\n runFunction: { for _ in 0..<$0 {\n benchmarkSequenceAlgos(s: c, n: c.count)\n benchmarkEquatableSequenceAlgos(s: c, n: c.count)\n }}, tags: t, setUpFunction: { blackHole(c) }, legacyFactor: 10),\n BenchmarkInfo(name: "SequenceAlgosRange", runFunction: { for _ in 0..<$0 {\n benchmarkSequenceAlgos(s: r, n: r.count)\n benchmarkEquatableSequenceAlgos(s: r, n: r.count)\n }}, tags: t, legacyFactor: 10),\n BenchmarkInfo(name: "SequenceAlgosUnfoldSequence",\n runFunction: { for _ in 0..<$0 {\n benchmarkSequenceAlgos(s: s, n: n)\n }}, tags: t, setUpFunction: { blackHole(s) }, legacyFactor: 10),\n BenchmarkInfo(name: "SequenceAlgosAnySequence",\n runFunction: { for _ in 0..<$0 {\n benchmarkSequenceAlgos(s: y, n: n/10)\n }}, tags: t, setUpFunction: { blackHole(y) }, legacyFactor: 100),\n]\n\nextension List: Sequence {\n struct Iterator: IteratorProtocol {\n var _list: List<Element>\n mutating func next() -> Element? {\n guard case let .node(x,xs) = _list else { return nil }\n _list = xs\n return x\n }\n }\n func makeIterator() -> Iterator {\n return Iterator(_list: self)\n }\n}\n\nextension List: Equatable where Element: Equatable {\n static func == (lhs: List<Element>, rhs: List<Element>) -> Bool {\n return lhs.elementsEqual(rhs)\n }\n}\n\nfunc benchmarkSequenceAlgos<S: Sequence>(s: S, n: Int) where S.Element == Int {\n check(s.reduce(0, &+) == (n*(n-1))/2)\n let mn = s.min()\n let mx = s.max()\n check(mn == 0 && mx == n-1)\n check(s.starts(with: s))\n}\n\nlet n = 1_000\nlet r = 0..<(n*100)\nlet l = List(0..<n)\nlet c = ContiguousArray(0..<(n*100))\nlet a = Array(0..<(n*100))\nlet y = AnySequence(0..<n/10)\nlet s = sequence(first: 0, next: { $0 < n&-1 ? $0&+1 : nil})\n\nfunc benchmarkEquatableSequenceAlgos<S: Sequence>(s: S, n: Int)\n where S.Element == Int, S: Equatable {\n check(repeatElement(s, count: 1).contains(s))\n check(!repeatElement(s, count: 1).contains { $0 != s })\n}\n\nenum List<Element> {\n case end\n indirect case node(Element, List<Element>)\n\n init<S: BidirectionalCollection>(_ elements: S) where S.Element == Element {\n self = elements.reversed().reduce(.end) { .node($1,$0) }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SequenceAlgos.swift | cpp_apple_swift_benchmark_single-source_SequenceAlgos.swift | Swift | 3,588 | 0.95 | 0.09 | 0.170455 | react-lib | 397 | 2023-08-20T02:15:00.784333 | MIT | false | c556bd7028272f141a24a1e8e517c2c0 |
//===--- SevenBoom.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Foundation\n\n// 15% _swift_allocObject (String.bridgeToObjectiveC)\n// 14% [NSError dealloc]\n// 14% objc_allocWithZone\n// 10% _swift_allocObject\n// 11% _swift_release_dealloc\n// 8% objc_release\n// 7% objc_msgSend\n// 5% _swift_release_\n// 2% _swift_retain_\npublic let benchmarks =\n BenchmarkInfo(\n name: "SevenBoom",\n runFunction: run_SevenBoom,\n tags: [.runtime, .exceptions, .bridging, .cpubench]\n )\n\n@inline(never)\nfunc filter_seven(_ input : Int) throws {\n guard case 7 = input else {\n throw NSError(domain: "AnDomain", code: 42, userInfo: nil)\n }\n}\n\n@inline(never)\npublic func run_SevenBoom(_ n: Int) {\n var c = 0\n for i in 1...n*5000 {\n do {\n try filter_seven(i)\n c += 1\n }\n catch _ {\n }\n }\n check(c == 1)\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SevenBoom.swift | cpp_apple_swift_benchmark_single-source_SevenBoom.swift | Swift | 1,303 | 0.95 | 0.096154 | 0.425532 | node-utils | 564 | 2024-07-14T13:19:12.217732 | MIT | false | 1ccdc43303c8ba869447eb0cabe3cdd1 |
//===--- Sim2DArray.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "Sim2DArray",\n runFunction: run_Sim2DArray,\n tags: [.validation, .api, .Array])\n\nstruct Array2D {\n var storage : [Int]\n let rows : Int\n let cols: Int\n\n init(numRows: Int, numCols: Int) {\n storage = [Int](repeating: 0, count: numRows * numCols)\n rows = numRows\n cols = numCols\n }\n}\n\n@inline(never)\nfunc workload_2DArrayTest(_ A: inout Array2D) {\n for _ in 0 ..< 10 {\n for r in 0 ..< A.rows {\n for c in 0 ..< A.cols {\n A.storage[r*A.cols+c] = 1\n }\n }\n }\n}\n\n@inline(never)\npublic func run_Sim2DArray(_ n: Int) {\n for _ in 0 ..< n {\n var a = Array2D(numRows:2048, numCols:32)\n workload_2DArrayTest(&a)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Sim2DArray.swift | cpp_apple_swift_benchmark_single-source_Sim2DArray.swift | Swift | 1,245 | 0.95 | 0.122449 | 0.25 | node-utils | 815 | 2025-05-29T17:58:31.354675 | BSD-3-Clause | false | 5219b34312d361dbaa52fd6913f378a1 |
//===--- SIMDRandomMask.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "SIMDRandomMask.Int8x16",\n runFunction: run_SIMDRandomMaskInt8x16,\n tags: [.validation, .SIMD]\n ),\n BenchmarkInfo(\n name: "SIMDRandomMask.Int8x64",\n runFunction: run_SIMDRandomMaskInt8x64,\n tags: [.validation, .SIMD]\n ),\n BenchmarkInfo(\n name: "SIMDRandomMask.Int64x2",\n runFunction: run_SIMDRandomMaskInt64x2,\n tags: [.validation, .SIMD]\n ),\n BenchmarkInfo(\n name: "SIMDRandomMask.Int64x8",\n runFunction: run_SIMDRandomMaskInt64x8,\n tags: [.validation, .SIMD]\n ),\n BenchmarkInfo(\n name: "SIMDRandomMask.Int64x64",\n runFunction: run_SIMDRandomMaskInt64x64,\n tags: [.validation, .SIMD]\n )\n]\n\n@inline(never)\npublic func run_SIMDRandomMaskInt8x16(_ n: Int) {\n var g = SplitMix64(seed: 0)\n var accum = SIMDMask<SIMD16<Int8>>()\n for _ in 0 ..< 10000*n {\n accum .^= SIMDMask.random(using: &g)\n }\n blackHole(accum)\n}\n\n@inline(never)\npublic func run_SIMDRandomMaskInt8x64(_ n: Int) {\n var g = SplitMix64(seed: 0)\n var accum = SIMDMask<SIMD64<Int8>>()\n for _ in 0 ..< 10000*n {\n accum .^= SIMDMask.random(using: &g)\n }\n blackHole(accum)\n}\n\n@inline(never)\npublic func run_SIMDRandomMaskInt64x2(_ n: Int) {\n var g = SplitMix64(seed: 0)\n var accum = SIMDMask<SIMD2<Int64>>()\n for _ in 0 ..< 10000*n {\n accum .^= SIMDMask.random(using: &g)\n }\n blackHole(accum)\n}\n\n@inline(never)\npublic func run_SIMDRandomMaskInt64x8(_ n: Int) {\n var g = SplitMix64(seed: 0)\n var accum = SIMDMask<SIMD8<Int64>>()\n for _ in 0 ..< 10000*n {\n accum .^= SIMDMask.random(using: &g)\n }\n blackHole(accum)\n}\n\n@inline(never)\npublic func run_SIMDRandomMaskInt64x64(_ n: Int) {\n var g = SplitMix64(seed: 0)\n var accum = SIMDMask<SIMD64<Int64>>()\n for _ in 0 ..< 10000*n {\n accum .^= SIMDMask.random(using: &g)\n }\n blackHole(accum)\n}\n \n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SIMDRandomMask.swift | cpp_apple_swift_benchmark_single-source_SIMDRandomMask.swift | Swift | 2,370 | 0.95 | 0.076087 | 0.130952 | python-kit | 822 | 2023-12-13T10:05:42.267594 | GPL-3.0 | false | 75bacd6360119f3c8a71c26578d1cc74 |
//===--- SIMDReduceInteger.swift ------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "SIMDReduce.Int32",\n runFunction: run_SIMDReduceInt32x1,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int32Data) }\n ),\n BenchmarkInfo(\n name: "SIMDReduce.Int32x4.Initializer",\n runFunction: run_SIMDReduceInt32x4_init,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int32Data) }\n ),\n BenchmarkInfo(\n name: "SIMDReduce.Int32x4.Cast",\n runFunction: run_SIMDReduceInt32x4_cast,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int32Data) }\n ), \n BenchmarkInfo(\n name: "SIMDReduce.Int32x16.Initializer",\n runFunction: run_SIMDReduceInt32x16_init,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int32Data) }\n ),\n BenchmarkInfo(\n name: "SIMDReduce.Int32x16.Cast",\n runFunction: run_SIMDReduceInt32x16_cast,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int32Data) }\n ),\n BenchmarkInfo(\n name: "SIMDReduce.Int8",\n runFunction: run_SIMDReduceInt8x1,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int8Data) }\n ),\n BenchmarkInfo(\n name: "SIMDReduce.Int8x16.Initializer",\n runFunction: run_SIMDReduceInt8x16_init,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int8Data) }\n ),\n BenchmarkInfo(\n name: "SIMDReduce.Int8x16.Cast",\n runFunction: run_SIMDReduceInt8x16_cast,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int8Data) }\n ),\n BenchmarkInfo(\n name: "SIMDReduce.Int8x64.Initializer",\n runFunction: run_SIMDReduceInt8x64_init,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int8Data) }\n ),\n BenchmarkInfo(\n name: "SIMDReduce.Int8x64.Cast",\n runFunction: run_SIMDReduceInt8x64_cast,\n tags: [.validation, .SIMD],\n setUpFunction: { blackHole(int8Data) }\n )\n]\n\n// TODO: use 100 for Onone?\nlet scale = 1000\n\nlet int32Data: UnsafeBufferPointer<Int32> = {\n let count = 256\n // Allocate memory for `count` Int32s with alignment suitable for all\n // SIMD vector types.\n let untyped = UnsafeMutableRawBufferPointer.allocate(\n byteCount: MemoryLayout<Int32>.size * count, alignment: 16\n )\n // Initialize the memory as Int32 and fill with random values.\n let typed = untyped.initializeMemory(as: Int32.self, repeating: 0)\n var g = SplitMix64(seed: 0)\n for i in 0 ..< typed.count {\n typed[i] = .random(in: .min ... .max, using: &g)\n }\n return UnsafeBufferPointer(typed)\n}()\n\n@inline(never)\npublic func run_SIMDReduceInt32x1(_ n: Int) {\n for _ in 0 ..< scale*n {\n var accum: Int32 = 0\n for v in int32Data {\n accum &+= v &* v\n }\n blackHole(accum)\n }\n}\n\n@inline(never)\npublic func run_SIMDReduceInt32x4_init(_ n: Int) {\n for _ in 0 ..< scale*n {\n var accum = SIMD4<Int32>()\n for i in stride(from: 0, to: int32Data.count, by: 4) {\n let v = SIMD4(int32Data[i ..< i+4])\n accum &+= v &* v\n }\n blackHole(accum.wrappedSum())\n }\n}\n\n@inline(never)\npublic func run_SIMDReduceInt32x4_cast(_ n: Int) {\n // Morally it seems like we "should" be able to use withMemoryRebound\n // to SIMD4<Int32>, but that function requires that the sizes match in\n // debug builds, so this is pretty ugly. The following "works" for now,\n // but is probably in violation of the formal model (the exact rules\n // for "assumingMemoryBound" are not clearly documented). We need a\n // better solution.\n let vecs = UnsafeBufferPointer<SIMD4<Int32>>(\n start: UnsafeRawPointer(int32Data.baseAddress!).assumingMemoryBound(to: SIMD4<Int32>.self),\n count: int32Data.count / 4\n )\n for _ in 0 ..< scale*n {\n var accum = SIMD4<Int32>()\n for v in vecs {\n accum &+= v &* v\n }\n blackHole(accum.wrappedSum())\n }\n}\n\n@inline(never)\npublic func run_SIMDReduceInt32x16_init(_ n: Int) {\n for _ in 0 ..< scale*n {\n var accum = SIMD16<Int32>()\n for i in stride(from: 0, to: int32Data.count, by: 16) {\n let v = SIMD16(int32Data[i ..< i+16])\n accum &+= v &* v\n }\n blackHole(accum.wrappedSum())\n }\n}\n\n@inline(never)\npublic func run_SIMDReduceInt32x16_cast(_ n: Int) {\n let vecs = UnsafeBufferPointer<SIMD16<Int32>>(\n start: UnsafeRawPointer(int32Data.baseAddress!).assumingMemoryBound(to: SIMD16<Int32>.self),\n count: int32Data.count / 16\n )\n for _ in 0 ..< scale*n {\n var accum = SIMD16<Int32>()\n for v in vecs {\n accum &+= v &* v\n }\n blackHole(accum.wrappedSum())\n }\n}\n\nlet int8Data: UnsafeBufferPointer<Int8> = {\n let count = 1024\n // Allocate memory for `count` Int8s with alignment suitable for all\n // SIMD vector types.\n let untyped = UnsafeMutableRawBufferPointer.allocate(\n byteCount: MemoryLayout<Int8>.size * count, alignment: 16\n )\n // Initialize the memory as Int8 and fill with random values.\n let typed = untyped.initializeMemory(as: Int8.self, repeating: 0)\n var g = SplitMix64(seed: 0)\n for i in 0 ..< typed.count {\n typed[i] = .random(in: .min ... .max, using: &g)\n }\n return UnsafeBufferPointer(typed)\n}()\n\n@inline(never)\npublic func run_SIMDReduceInt8x1(_ n: Int) {\n for _ in 0 ..< scale*n {\n var accum: Int8 = 0\n for v in int8Data {\n accum &+= v &* v\n }\n blackHole(accum)\n }\n}\n\n@inline(never)\npublic func run_SIMDReduceInt8x16_init(_ n: Int) {\n for _ in 0 ..< scale*n {\n var accum = SIMD16<Int8>()\n for i in stride(from: 0, to: int8Data.count, by: 16) {\n let v = SIMD16(int8Data[i ..< i+16])\n accum &+= v &* v\n }\n blackHole(accum.wrappedSum())\n }\n}\n\n@inline(never)\npublic func run_SIMDReduceInt8x16_cast(_ n: Int) {\n let vecs = UnsafeBufferPointer<SIMD16<Int8>>(\n start: UnsafeRawPointer(int8Data.baseAddress!).assumingMemoryBound(to: SIMD16<Int8>.self),\n count: int8Data.count / 16\n )\n for _ in 0 ..< scale*n {\n var accum = SIMD16<Int8>()\n for v in vecs {\n accum &+= v &* v\n }\n blackHole(accum.wrappedSum())\n }\n}\n\n@inline(never)\npublic func run_SIMDReduceInt8x64_init(_ n: Int) {\n for _ in 0 ..< scale*n {\n var accum = SIMD64<Int8>()\n for i in stride(from: 0, to: int8Data.count, by: 64) {\n let v = SIMD64(int8Data[i ..< i+64])\n accum &+= v &* v\n }\n blackHole(accum.wrappedSum())\n }\n}\n\n@inline(never)\npublic func run_SIMDReduceInt8x64_cast(_ n: Int) {\n let vecs = UnsafeBufferPointer<SIMD64<Int8>>(\n start: UnsafeRawPointer(int8Data.baseAddress!).assumingMemoryBound(to: SIMD64<Int8>.self),\n count: int8Data.count / 64\n )\n for _ in 0 ..< scale*n {\n var accum = SIMD64<Int8>()\n for v in vecs {\n accum &+= v &* v\n }\n blackHole(accum.wrappedSum())\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SIMDReduceInteger.swift | cpp_apple_swift_benchmark_single-source_SIMDReduceInteger.swift | Swift | 7,085 | 0.95 | 0.129555 | 0.103448 | awesome-app | 977 | 2024-08-29T05:23:20.010854 | GPL-3.0 | false | 38b8ec630e35d55ff7f263394a6e1eaf |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This benchmark tests prespecialization of a simplified array type\n\nimport TestsUtils\nimport SimpleArray\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "SimpleArraySpecialization",\n runFunction: run_SimpleArraySpecializationBenchmarks,\n tags: [.abstraction, .runtime, .cpubench]\n ),\n BenchmarkInfo(\n name: "SimpleArraySpecialization2",\n runFunction: run_SimpleArraySpecializationBenchmarks2,\n tags: [.abstraction, .runtime, .cpubench]\n ),\n BenchmarkInfo(\n name: "SimpleArraySpecialization3",\n runFunction: run_SimpleArraySpecializationBenchmarks3,\n tags: [.abstraction, .runtime, .cpubench]\n ),\n BenchmarkInfo(\n name: "SimpleArraySpecialization4",\n runFunction: run_SimpleArraySpecializationBenchmarks4,\n tags: [.abstraction, .runtime, .cpubench]\n ),\n]\n\nlet xs = SimpleArray<MyClass>(capacity: 100_000)\n\n@_silgen_name("_swift_stdlib_immortalize")\nfunc _stdlib_immortalize(_ obj: AnyObject)\n\nimport Foundation\n\n\npublic final class MyClass {\n public var x: Int = 23\n}\n\n\n@inline(never)\npublic func run_SimpleArraySpecializationBenchmarks(_ n: Int) {\n let myObject = MyClass()\n\n // prevent refcount overflow\n _stdlib_immortalize(myObject)\n \n for _ in 0..<n {\n for i in 0..<100_000 {\n xs.append(myObject)\n }\n xs.clear()\n }\n\n blackHole(xs)\n}\n\n@inline(never)\npublic func run_SimpleArraySpecializationBenchmarks2(_ n: Int) {\n let myObject = MyClass()\n \n // prevent refcount overflow\n _stdlib_immortalize(myObject)\n\n for _ in 0..<n {\n for i in 0..<100_000 {\n xs.append2(myObject)\n }\n xs.clear()\n }\n\n blackHole(xs)\n}\n\n@inline(never)\npublic func run_SimpleArraySpecializationBenchmarks3(_ n: Int) {\n let myObject = MyClass()\n \n // prevent refcount overflow\n _stdlib_immortalize(myObject)\n\n for _ in 0..<n {\n for i in 0..<100_000 {\n xs.append3(myObject)\n }\n xs.clear()\n }\n\n blackHole(xs)\n}\n\n@inline(never)\npublic func run_SimpleArraySpecializationBenchmarks4(_ n: Int) {\n let myObject = MyClass()\n \n // prevent refcount overflow\n _stdlib_immortalize(myObject)\n\n for _ in 0..<n {\n for i in 0..<100_000 {\n xs.append4(myObject)\n }\n xs.clear()\n }\n\n blackHole(xs)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SimpleArraySpecialization.swift | cpp_apple_swift_benchmark_single-source_SimpleArraySpecialization.swift | Swift | 2,696 | 0.95 | 0.091667 | 0.168421 | react-lib | 884 | 2023-07-24T20:33:10.520370 | BSD-3-Clause | false | 98b0683ca115deb1e8c542ab5add7726 |
//===--- SortArrayInClass.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n// This benchmark is derived from user code that encountered a major\n// performance problem in normal usage. Contributed by Saleem\n// Abdulrasool (compnerd).\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\n// Specifically tests efficient access to Array subscript when the\n// array is a class property, but also generally tests quicksort in a\n// class which needs a slew of array optimizations, uniqueness, bounds\n// and exclusivity optimizations.\npublic let benchmarks = [\n BenchmarkInfo(\n name: "SortArrayInClass",\n runFunction: run_SortArrayInClass,\n tags: [.abstraction, .safetychecks, .exclusivity, .algorithm, .api, .Array])\n]\n\nlet largeArraySize = 10000\n\nclass Sorter {\n var array: [Int]\n init(size: Int) {\n array = Array((0..<size).reversed())\n }\n\n private func _swap(i: Int, j: Int) {\n let t = array[i]\n // This currently copies the entire array. Assigning to a\n // temporary, or using swapAt would avoid the copy, but users\n // shouldn't need to know that.\n array[i] = array[j]\n array[j] = t\n }\n\n private func _quicksort(left: Int, right: Int) {\n\n if left < right {\n let pivot = array[left + ((right - left) / 2)]\n var left_new = left\n var right_new = right\n\n repeat {\n while array[left_new] < pivot {\n left_new += 1\n }\n while pivot < array[right_new] {\n right_new -= 1\n }\n if left_new <= right_new {\n _swap(i:left_new, j:right_new)\n left_new += 1\n right_new -= 1\n }\n } while left_new <= right_new\n\n _quicksort(left: left, right: right_new)\n _quicksort(left: left_new, right:right)\n }\n }\n\n func quicksort() {\n _quicksort(left:0, right:array.count - 1);\n }\n}\n\npublic func run_SortArrayInClass(_ n: Int) {\n for _ in 1...n {\n // The array needs to be reinitialized before each sort, so it\n // can't be a setup/tearDown function.\n let sorter = Sorter(size: largeArraySize)\n sorter.quicksort()\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SortArrayInClass.swift | cpp_apple_swift_benchmark_single-source_SortArrayInClass.swift | Swift | 2,484 | 0.95 | 0.141176 | 0.324324 | node-utils | 664 | 2024-10-11T10:53:23.455349 | GPL-3.0 | false | dc7eedb5f35e3cbf92df7b02f626c53c |
import TestsUtils\n\n// This benchmark aims to measure heapSort path of stdlib sorting function.\n// Datasets in this benchmark are influenced by stdlib partition function,\n// therefore if stdlib partition implementation changes we should correct these\n// datasets or disable/skip this benchmark\npublic let benchmarks = [\n BenchmarkInfo(\n name: "SortIntPyramid",\n runFunction: run_SortIntPyramid,\n tags: [.validation, .api, .algorithm],\n legacyFactor: 5),\n BenchmarkInfo(\n name: "SortAdjacentIntPyramids",\n runFunction: run_SortAdjacentIntPyramids,\n tags: [.validation, .api, .algorithm],\n legacyFactor: 5),\n]\n\n// let A - array sorted in ascending order,\n// A^R - reversed array A, + - array concatenation operator\n// A indices are in range 1...A.length\n// define the pyramid as A + A^R\n// define pyramid height as A[A.length]\n\n// On 92% of following dataset stdlib sorting function will use heapSort.\n// number of ranges sorted by heapSort: 26\n// median heapSort range length: 198\n// maximum -||-: 1774\n// average -||-: 357\n\n// pyramid height\nlet pH = 5000\nlet pyramidTemplate: [Int] = (1...pH) + (1...pH).reversed()\n\n// let A - array sorted in ascending order,\n// A^R - reversed array A, + - array concatenation operator,\n// A indices are in range 1...A.length.\n// define adjacent pyramid as A + A^R + A + A^R,\n// define adjacent pyramid height as A[A.length].\n\n\n// On 25% of following dataset stdlib sorting function will use heapSort.\n// number of ranges sorted by heapSort: 71\n// median heapSort range length: 28\n// maximum -||-: 120\n// average -||-: 36\n\n// adjacent pyramids height.\nlet aPH = pH / 2\nlet adjacentPyramidsTemplate: [Int] = (1...aPH) + (1...aPH).reversed()\n + (1...aPH) + (1...aPH).reversed()\n\n@inline(never)\npublic func run_SortIntPyramid(_ n: Int) {\n for _ in 1...5*n {\n var pyramid = pyramidTemplate\n\n // sort pyramid in place.\n pyramid.sort()\n\n // Check whether pyramid is sorted.\n check(pyramid[0] <= pyramid[pyramid.count/2])\n }\n}\n\n@inline(never)\npublic func run_SortAdjacentIntPyramids(_ n: Int) {\n for _ in 1...5*n {\n var adjacentPyramids = adjacentPyramidsTemplate\n adjacentPyramids.sort()\n // Check whether pyramid is sorted.\n check(\n adjacentPyramids[0] <= adjacentPyramids[adjacentPyramids.count/2])\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SortIntPyramids.swift | cpp_apple_swift_benchmark_single-source_SortIntPyramids.swift | Swift | 2,331 | 0.95 | 0.092105 | 0.453125 | react-lib | 716 | 2024-01-08T15:24:34.275955 | Apache-2.0 | false | 6f5fb7cd05a99c0a11f315767ce2407d |
//===--- SortLargeExistentials.swift --------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test is a variant of the SortLettersInPlace.\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "SortLargeExistentials",\n runFunction: run_SortLargeExistentials,\n tags: [.validation, .api, .algorithm, .cpubench],\n legacyFactor: 100),\n]\n\nprotocol LetterKind {\n var value: String { get }\n func lessthan(_ rhs: LetterKind) -> Bool\n}\n\n// A struct which exceeds the size of the existential inline buffer.\nstruct Letter : LetterKind {\n let value: String\n\n // Make this struct a large struct which does not fit into the 3-word\n // existential inline buffer. Also provide an answer to ...\n var a: Int = 42\n var b: Int = 42\n var c: Int = 42\n var d: Int = 42\n\n init(_ value: String) {\n self.value = value\n }\n\n func lessthan(_ rhs: LetterKind) -> Bool {\n return value < rhs.value\n }\n}\n\nlet lettersTemplate : [LetterKind] = [\n Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"),\n Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"),\n Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"),\n Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"),\n Letter("z"), Letter("g"),\n Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"),\n Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"),\n Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"),\n Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"),\n Letter("z"), Letter("g"),\n Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"),\n Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"),\n Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"),\n Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"),\n Letter("z"), Letter("g"),\n Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"),\n Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"),\n Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"),\n Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"),\n Letter("z"), Letter("g"),\n Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"),\n Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"),\n Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"),\n Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"),\n Letter("z"), Letter("g")\n]\n\n@inline(never)\npublic func run_SortLargeExistentials(_ n: Int) {\n for _ in 1...n {\n var letters = lettersTemplate\n\n letters.sort {\n return $0.lessthan($1)\n }\n\n // Check whether letters are sorted.\n check(letters[0].value <= letters[letters.count/2].value)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SortLargeExistentials.swift | cpp_apple_swift_benchmark_single-source_SortLargeExistentials.swift | Swift | 3,417 | 0.95 | 0.033333 | 0.205128 | node-utils | 999 | 2023-08-06T11:43:03.014844 | MIT | false | 60ed326d22041eb5b4d4a3e1fd9c95f1 |
//===--- SortLettersInPlace.swift -----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance and correctness of Swift sortInPlace on an\n// array of letters.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "SortLettersInPlace",\n runFunction: run_SortLettersInPlace,\n tags: [.validation, .api, .algorithm, .String])\n\nclass Letter {\n let value: String\n init(_ value: String) {\n self.value = value\n }\n}\n\n@inline(never)\npublic func run_SortLettersInPlace(_ n: Int) {\n for _ in 1...100*n {\n var letters = [\n Letter("k"), Letter("a"), Letter("x"), Letter("i"), Letter("f"), Letter("l"),\n Letter("o"), Letter("w"), Letter("h"), Letter("p"), Letter("b"), Letter("u"),\n Letter("n"), Letter("c"), Letter("j"), Letter("t"), Letter("y"), Letter("s"),\n Letter("d"), Letter("v"), Letter("r"), Letter("e"), Letter("q"), Letter("m"),\n Letter("z"), Letter("g")\n ]\n\n // Sort the letters in place.\n letters.sort {\n return $0.value < $1.value\n }\n\n // Check whether letters are sorted.\n check(letters[0].value <= letters[letters.count/2].value)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SortLettersInPlace.swift | cpp_apple_swift_benchmark_single-source_SortLettersInPlace.swift | Swift | 1,584 | 0.95 | 0.081633 | 0.348837 | node-utils | 221 | 2024-01-07T00:57:17.880222 | BSD-3-Clause | false | 64fdc8d6561c90a4fb1f53a3ec485432 |
//===--- SortStrings.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport TestsUtils\n\nlet t: [BenchmarkCategory] = [.validation, .api, .algorithm, .String]\n// Sort an array of strings using an explicit sort predicate.\npublic let benchmarks = [\n BenchmarkInfo(name: "SortSortedStrings",\n runFunction: run_SortSortedStrings, tags: t,\n setUpFunction: { blackHole(sortedWords) }),\n BenchmarkInfo(name: "SortStrings",\n runFunction: run_SortStrings, tags: t,\n setUpFunction: { blackHole(words) }),\n BenchmarkInfo(name: "SortStringsUnicode",\n runFunction: run_SortStringsUnicode, tags: t,\n setUpFunction: { blackHole(unicodeWords) }, legacyFactor: 5),\n]\n\nlet sortedWords = words.sorted()\nlet words: [String] = [\n "woodshed",\n "lakism",\n "gastroperiodynia",\n "afetal",\n "ramsch",\n "Nickieben",\n "undutifulness",\n "birdglue",\n "ungentlemanize",\n "menacingly",\n "heterophile",\n "leoparde",\n "Casearia",\n "decorticate",\n "neognathic",\n "mentionable",\n "tetraphenol",\n "pseudonymal",\n "dislegitimate",\n "Discoidea",\n "intitule",\n "ionium",\n "Lotuko",\n "timbering",\n "nonliquidating",\n "oarialgia",\n "Saccobranchus",\n "reconnoiter",\n "criminative",\n "disintegratory",\n "executer",\n "Cylindrosporium",\n "complimentation",\n "Ixiama",\n "Araceae",\n "silaginoid",\n "derencephalus",\n "Lamiidae",\n "marrowlike",\n "ninepin",\n "dynastid",\n "lampfly",\n "feint",\n "trihemimer",\n "semibarbarous",\n "heresy",\n "tritanope",\n "indifferentist",\n "confound",\n "hyperbolaeon",\n "planirostral",\n "philosophunculist",\n "existence",\n "fretless",\n "Leptandra",\n "Amiranha",\n "handgravure",\n "gnash",\n "unbelievability",\n "orthotropic",\n "Susumu",\n "teleutospore",\n "sleazy",\n "shapeliness",\n "hepatotomy",\n "exclusivism",\n "stifler",\n "cunning",\n "isocyanuric",\n "pseudepigraphy",\n "carpetbagger",\n "respectiveness",\n "Jussi",\n "vasotomy",\n "proctotomy",\n "ovatotriangular",\n "aesthetic",\n "schizogamy",\n "disengagement",\n "foray",\n "haplocaulescent",\n "noncoherent",\n "astrocyte",\n "unreverberated",\n "presenile",\n "lanson",\n "enkraal",\n "contemplative",\n "Syun",\n "sartage",\n "unforgot",\n "wyde",\n "homeotransplant",\n "implicational",\n "forerunnership",\n "calcaneum",\n "stomatodeum",\n "pharmacopedia",\n "preconcessive",\n "trypanosomatic",\n "intracollegiate",\n "rampacious",\n "secundipara",\n "isomeric",\n "treehair",\n "pulmonal",\n "uvate",\n "dugway",\n "glucofrangulin",\n "unglory",\n "Amandus",\n "icterogenetic",\n "quadrireme",\n "Lagostomus",\n "brakeroot",\n "anthracemia",\n "fluted",\n "protoelastose",\n "thro",\n "pined",\n "Saxicolinae",\n "holidaymaking",\n "strigil",\n "uncurbed",\n "starling",\n "redeemeress",\n "Liliaceae",\n "imparsonee",\n "obtusish",\n "brushed",\n "mesally",\n "probosciformed",\n "Bourbonesque",\n "histological",\n "caroba",\n "digestion",\n "Vindemiatrix",\n "triactinal",\n "tattling",\n "arthrobacterium",\n "unended",\n "suspectfulness",\n "movelessness",\n "chartist",\n "Corynebacterium",\n "tercer",\n "oversaturation",\n "Congoleum",\n "antiskeptical",\n "sacral",\n "equiradiate",\n "whiskerage",\n "panidiomorphic",\n "unplanned",\n "anilopyrine",\n "Queres",\n "tartronyl",\n "Ing",\n "notehead",\n "finestiller",\n "weekender",\n "kittenhood",\n "competitrix",\n "premillenarian",\n "convergescence",\n "microcoleoptera",\n "slirt",\n "asteatosis",\n "Gruidae",\n "metastome",\n "ambuscader",\n "untugged",\n "uneducated",\n "redistill",\n "rushlight",\n "freakish",\n "dosology",\n "papyrine",\n "iconologist",\n "Bidpai",\n "prophethood",\n "pneumotropic",\n "chloroformize",\n "intemperance",\n "spongiform",\n "superindignant",\n "divider",\n "starlit",\n "merchantish",\n "indexless",\n "unidentifiably",\n "coumarone",\n "nomism",\n "diaphanous",\n "salve",\n "option",\n "anallantoic",\n "paint",\n "thiofurfuran",\n "baddeleyite",\n "Donne",\n "heterogenicity",\n "decess",\n "eschynite",\n "mamma",\n "unmonarchical",\n "Archiplata",\n "widdifow",\n "apathic",\n "overline",\n "chaetophoraceous",\n "creaky",\n "trichosporange",\n "uninterlined",\n "cometwise",\n "hermeneut",\n "unbedraggled",\n "tagged",\n "Sminthurus",\n "somniloquacious",\n "aphasiac",\n "Inoperculata",\n "photoactivity",\n "mobship",\n "unblightedly",\n "lievrite",\n "Khoja",\n "Falerian",\n "milfoil",\n "protectingly",\n "householder",\n "cathedra",\n "calmingly",\n "tordrillite",\n "rearhorse",\n "Leonard",\n "maracock",\n "youngish",\n "kammererite",\n "metanephric",\n "Sageretia",\n "diplococcoid",\n "accelerative",\n "choreal",\n "metalogical",\n "recombination",\n "unimprison",\n "invocation",\n "syndetic",\n "toadback",\n "vaned",\n "cupholder",\n "metropolitanship",\n "paramandelic",\n "dermolysis",\n "Sheriyat",\n "rhabdus",\n "seducee",\n "encrinoid",\n "unsuppliable",\n "cololite",\n "timesaver",\n "preambulate",\n "sampling",\n "roaster",\n "springald",\n "densher",\n "protraditional",\n "naturalesque",\n "Hydrodamalis",\n "cytogenic",\n "shortly",\n "cryptogrammatical",\n "squat",\n "genual",\n "backspier",\n "solubleness",\n "macroanalytical",\n "overcovetousness",\n "Natalie",\n "cuprobismutite",\n "phratriac",\n "Montanize",\n "hymnologist",\n "karyomiton",\n "podger",\n "unofficiousness",\n "antisplasher",\n "supraclavicular",\n "calidity",\n "disembellish",\n "antepredicament",\n "recurvirostral",\n "pulmonifer",\n "coccidial",\n "botonee",\n "protoglobulose",\n "isonym",\n "myeloid",\n "premiership",\n "unmonopolize",\n "unsesquipedalian",\n "unfelicitously",\n "theftbote",\n "undauntable",\n "lob",\n "praenomen",\n "underriver",\n "gorfly",\n "pluckage",\n "radiovision",\n "tyrantship",\n "fraught",\n "doppelkummel",\n "rowan",\n "allosyndetic",\n "kinesiology",\n "psychopath",\n "arrent",\n "amusively",\n "preincorporation",\n "Montargis",\n "pentacron",\n "neomedievalism",\n "sima",\n "lichenicolous",\n "Ecclesiastes",\n "woofed",\n "cardinalist",\n "sandaracin",\n "gymnasial",\n "lithoglyptics",\n "centimeter",\n "quadrupedous",\n "phraseology",\n "tumuli",\n "ankylotomy",\n "myrtol",\n "cohibitive",\n "lepospondylous",\n "silvendy",\n "inequipotential",\n "entangle",\n "raveling",\n "Zeugobranchiata",\n "devastating",\n "grainage",\n "amphisbaenian",\n "blady",\n "cirrose",\n "proclericalism",\n "governmentalist",\n "carcinomorphic",\n "nurtureship",\n "clancular",\n "unsteamed",\n "discernibly",\n "pleurogenic",\n "impalpability",\n "Azotobacterieae",\n "sarcoplasmic",\n "alternant",\n "fitly",\n "acrorrheuma",\n "shrapnel",\n "pastorize",\n "gulflike",\n "foreglow",\n "unrelated",\n "cirriped",\n "cerviconasal",\n "sexuale",\n "pussyfooter",\n "gadolinic",\n "duplicature",\n "codelinquency",\n "trypanolysis",\n "pathophobia",\n "incapsulation",\n "nonaerating",\n "feldspar",\n "diaphonic",\n "epiglottic",\n "depopulator",\n "wisecracker",\n "gravitational",\n "kuba",\n "lactesce",\n "Toxotes",\n "periomphalic",\n "singstress",\n "fannier",\n "counterformula",\n "Acemetae",\n "repugnatorial",\n "collimator",\n "Acinetina",\n "unpeace",\n "drum",\n "tetramorphic",\n "descendentalism",\n "cementer",\n "supraloral",\n "intercostal",\n "Nipponize",\n "negotiator",\n "vacationless",\n "synthol",\n "fissureless",\n "resoap",\n "pachycarpous",\n "reinspiration",\n "misappropriation",\n "disdiazo",\n "unheatable",\n "streng",\n "Detroiter",\n "infandous",\n "loganiaceous",\n "desugar",\n "Matronalia",\n "myxocystoma",\n "Gandhiism",\n "kiddier",\n "relodge",\n "counterreprisal",\n "recentralize",\n "foliously",\n "reprinter",\n "gender",\n "edaciousness",\n "chondriomite",\n "concordant",\n "stockrider",\n "pedary",\n "shikra",\n "blameworthiness",\n "vaccina",\n "Thamnophilinae",\n "wrongwise",\n "unsuperannuated",\n "convalescency",\n "intransmutable",\n "dropcloth",\n "Ceriomyces",\n "ponderal",\n "unstentorian",\n "mem",\n "deceleration",\n "ethionic",\n "untopped",\n "wetback",\n "bebar",\n "undecaying",\n "shoreside",\n "energize",\n "presacral",\n "undismay",\n "agricolite",\n "cowheart",\n "hemibathybian",\n "postexilian",\n "Phacidiaceae",\n "offing",\n "redesignation",\n "skeptically",\n "physicianless",\n "bronchopathy",\n "marabuto",\n "proprietory",\n "unobtruded",\n "funmaker",\n "plateresque",\n "preadventure",\n "beseeching",\n "cowpath",\n "pachycephalia",\n "arthresthesia",\n "supari",\n "lengthily",\n "Nepa",\n "liberation",\n "nigrify",\n "belfry",\n "entoolitic",\n "bazoo",\n "pentachromic",\n "distinguishable",\n "slideable",\n "galvanoscope",\n "remanage",\n "cetene",\n "bocardo",\n "consummation",\n "boycottism",\n "perplexity",\n "astay",\n "Gaetuli",\n "periplastic",\n "consolidator",\n "sluggarding",\n "coracoscapular",\n "anangioid",\n "oxygenizer",\n "Hunanese",\n "seminary",\n "periplast",\n "Corylus",\n "unoriginativeness",\n "persecutee",\n "tweaker",\n "silliness",\n "Dabitis",\n "facetiousness",\n "thymy",\n "nonimperial",\n "mesoblastema",\n "turbiniform",\n "churchway",\n "cooing",\n "frithbot",\n "concomitantly",\n "stalwartize",\n "clingfish",\n "hardmouthed",\n "parallelepipedonal",\n "coracoacromial",\n "factuality",\n "curtilage",\n "arachnoidean",\n "semiaridity",\n "phytobacteriology",\n "premastery",\n "hyperpurist",\n "mobed",\n "opportunistic",\n "acclimature",\n "outdistance",\n "sophister",\n "condonement",\n "oxygenerator",\n "acetonic",\n "emanatory",\n "periphlebitis",\n "nonsociety",\n "spectroradiometric",\n "superaverage",\n "cleanness",\n "posteroventral",\n "unadvised",\n "unmistakedly",\n "pimgenet",\n "auresca",\n "overimitate",\n "dipnoan",\n "chromoxylograph",\n "triakistetrahedron",\n "Suessiones",\n "uncopiable",\n "oligomenorrhea",\n "fribbling",\n "worriable",\n "flot",\n "ornithotrophy",\n "phytoteratology",\n "setup",\n "lanneret",\n "unbraceleted",\n "gudemother",\n "Spica",\n "unconsolatory",\n "recorruption",\n "premenstrual",\n "subretinal",\n "millennialist",\n "subjectibility",\n "rewardproof",\n "counterflight",\n "pilomotor",\n "carpetbaggery",\n "macrodiagonal",\n "slim",\n "indiscernible",\n "cuckoo",\n "moted",\n "controllingly",\n "gynecopathy",\n "porrectus",\n "wanworth",\n "lutfisk",\n "semiprivate",\n "philadelphy",\n "abdominothoracic",\n "coxcomb",\n "dambrod",\n "Metanemertini",\n "balminess",\n "homotypy",\n "waremaker",\n "absurdity",\n "gimcrack",\n "asquat",\n "suitable",\n "perimorphous",\n "kitchenwards",\n "pielum",\n "salloo",\n "paleontologic",\n "Olson",\n "Tellinidae",\n "ferryman",\n "peptonoid",\n "Bopyridae",\n "fallacy",\n "ictuate",\n "aguinaldo",\n "rhyodacite",\n "Ligydidae",\n "galvanometric",\n "acquisitor",\n "muscology",\n "hemikaryon",\n "ethnobotanic",\n "postganglionic",\n "rudimentarily",\n "replenish",\n "phyllorhine",\n "popgunnery",\n "summar",\n "quodlibetary",\n "xanthochromia",\n "autosymbolically",\n "preloreal",\n "extent",\n "strawberry",\n "immortalness",\n "colicwort",\n "frisca",\n "electiveness",\n "heartbroken",\n "affrightingly",\n "reconfiscation",\n "jacchus",\n "imponderably",\n "semantics",\n "beennut",\n "paleometeorological",\n "becost",\n "timberwright",\n "resuppose",\n "syncategorematical",\n "cytolymph",\n "steinbok",\n "explantation",\n "hyperelliptic",\n "antescript",\n "blowdown",\n "antinomical",\n "caravanserai",\n "unweariedly",\n "isonymic",\n "keratoplasty",\n "vipery",\n "parepigastric",\n "endolymphatic",\n "Londonese",\n "necrotomy",\n "angelship",\n "Schizogregarinida",\n "steeplebush",\n "sparaxis",\n "connectedness",\n "tolerance",\n "impingent",\n "agglutinin",\n "reviver",\n "hieroglyphical",\n "dialogize",\n "coestate",\n "declamatory",\n "ventilation",\n "tauromachy",\n "cotransubstantiate",\n "pome",\n "underseas",\n "triquadrantal",\n "preconfinemnt",\n "electroindustrial",\n "selachostomous",\n "nongolfer",\n "mesalike",\n "hamartiology",\n "ganglioblast",\n "unsuccessive",\n "yallow",\n "bacchanalianly",\n "platydactyl",\n "Bucephala",\n "ultraurgent",\n "penalist",\n "catamenial",\n "lynnhaven",\n "unrelevant",\n "lunkhead",\n "metropolitan",\n "hydro",\n "outsoar",\n "vernant",\n "interlanguage",\n "catarrhal",\n "Ionicize",\n "keelless",\n "myomantic",\n "booker",\n "Xanthomonas",\n "unimpeded",\n "overfeminize",\n "speronaro",\n "diaconia",\n "overholiness",\n "liquefacient",\n "Spartium",\n "haggly",\n "albumose",\n "nonnecessary",\n "sulcalization",\n "decapitate",\n "cellated",\n "unguirostral",\n "trichiurid",\n "loveproof",\n "amakebe",\n "screet",\n "arsenoferratin",\n "unfrizz",\n "undiscoverable",\n "procollectivistic",\n "tractile",\n "Winona",\n "dermostosis",\n "eliminant",\n "scomberoid",\n "tensile",\n "typesetting",\n "xylic",\n "dermatopathology",\n "cycloplegic",\n "revocable",\n "fissate",\n "afterplay",\n "screwship",\n "microerg",\n "bentonite",\n "stagecoaching",\n "beglerbeglic",\n "overcharitably",\n "Plotinism",\n "Veddoid",\n "disequalize",\n "cytoproct",\n "trophophore",\n "antidote",\n "allerion",\n "famous",\n "convey",\n "postotic",\n "rapillo",\n "cilectomy",\n "penkeeper",\n "patronym",\n "bravely",\n "ureteropyelitis",\n "Hildebrandine",\n "missileproof",\n "Conularia",\n "deadening",\n "Conrad",\n "pseudochylous",\n "typologically",\n "strummer",\n "luxuriousness",\n "resublimation",\n "glossiness",\n "hydrocauline",\n "anaglyph",\n "personifiable",\n "seniority",\n "formulator",\n "datiscaceous",\n "hydracrylate",\n "Tyranni",\n "Crawthumper",\n "overprove",\n "masher",\n "dissonance",\n "Serpentinian",\n "malachite",\n "interestless",\n "stchi",\n "ogum",\n "polyspermic",\n "archegoniate",\n "precogitation",\n "Alkaphrah",\n "craggily",\n "delightfulness",\n "bioplast",\n "diplocaulescent",\n "neverland",\n "interspheral",\n "chlorhydric",\n "forsakenly",\n "scandium",\n "detubation",\n "telega",\n "Valeriana",\n "centraxonial",\n "anabolite",\n "neger",\n "miscellanea",\n "whalebacker",\n "stylidiaceous",\n "unpropelled",\n "Kennedya",\n "Jacksonite",\n "ghoulish",\n "Dendrocalamus",\n "paynimhood",\n "rappist",\n "unluffed",\n "falling",\n "Lyctus",\n "uncrown",\n "warmly",\n "pneumatism",\n "Morisonian",\n "notate",\n "isoagglutinin",\n "Pelidnota",\n "previsit",\n "contradistinctly",\n "utter",\n "porometer",\n "gie",\n "germanization",\n "betwixt",\n "prenephritic",\n "underpier",\n "Eleutheria",\n "ruthenious",\n "convertor",\n "antisepsin",\n "winterage",\n "tetramethylammonium",\n "Rockaway",\n "Penaea",\n "prelatehood",\n "brisket",\n "unwishful",\n "Minahassa",\n "Briareus",\n "semiaxis",\n "disintegrant",\n "peastick",\n "iatromechanical",\n "fastus",\n "thymectomy",\n "ladyless",\n "unpreened",\n "overflutter",\n "sicker",\n "apsidally",\n "thiazine",\n "guideway",\n "pausation",\n "tellinoid",\n "abrogative",\n "foraminulate",\n "omphalos",\n "Monorhina",\n "polymyarian",\n "unhelpful",\n "newslessness",\n "oryctognosy",\n "octoradial",\n "doxology",\n "arrhythmy",\n "gugal",\n "mesityl",\n "hexaplaric",\n "Cabirian",\n "hordeiform",\n "eddyroot",\n "internarial",\n "deservingness",\n "jawbation",\n "orographically",\n "semiprecious",\n "seasick",\n "thermically",\n "grew",\n "tamability",\n "egotistically",\n "fip",\n "preabsorbent",\n "leptochroa",\n "ethnobotany",\n "podolite",\n "egoistic",\n "semitropical",\n "cero",\n "spinelessness",\n "onshore",\n "omlah",\n "tintinnabulist",\n "machila",\n "entomotomy",\n "nubile",\n "nonscholastic",\n "burnt",\n "Alea",\n "befume",\n "doctorless",\n "Napoleonic",\n "scenting",\n "apokreos",\n "cresylene",\n "paramide",\n "rattery",\n "disinterested",\n "idiopathetic",\n "negatory",\n "fervid",\n "quintato",\n "untricked",\n "Metrosideros",\n "mescaline",\n "midverse",\n "Musophagidae",\n "fictionary",\n "branchiostegous",\n "yoker",\n "residuum",\n "culmigenous",\n "fleam",\n "suffragism",\n "Anacreon",\n "sarcodous",\n "parodistic",\n "writmaking",\n "conversationism",\n "retroposed",\n "tornillo",\n "presuspect",\n "didymous",\n "Saumur",\n "spicing",\n "drawbridge",\n "cantor",\n "incumbrancer",\n "heterospory",\n "Turkeydom",\n "anteprandial",\n "neighborship",\n "thatchless",\n "drepanoid",\n "lusher",\n "paling",\n "ecthlipsis",\n "heredosyphilitic",\n "although",\n "garetta",\n "temporarily",\n "Monotropa",\n "proglottic",\n "calyptro",\n "persiflage",\n "degradable",\n "paraspecific",\n "undecorative",\n "Pholas",\n "myelon",\n "resteal",\n "quadrantly",\n "scrimped",\n "airer",\n "deviless",\n "caliciform",\n "Sefekhet",\n "shastaite",\n "togate",\n "macrostructure",\n "bipyramid",\n "wey",\n "didynamy",\n "knacker",\n "swage",\n "supermanism",\n "epitheton",\n "overpresumptuous"\n ]\n\n\n@inline(never)\nfunc benchSortStrings(_ words: [String]) {\n // Notice that we _copy_ the array of words before we sort it.\n // Pass an explicit '<' predicate to benchmark reabstraction thunks.\n var tempwords = words\n tempwords.sort(by: <)\n}\n\npublic func run_SortStrings(_ n: Int) {\n for _ in 1...5*n {\n benchSortStrings(words)\n }\n}\n\npublic func run_SortSortedStrings(_ n: Int) {\n for _ in 1...5*n {\n benchSortStrings(sortedWords)\n }\n}\n\nlet unicodeWords: [String] = [\n "❄️woodshed",\n "❄️lakism",\n "❄️gastroperiodynia",\n "❄️afetal",\n "❄️ramsch",\n "❄️Nickieben",\n "❄️undutifulness",\n "❄️birdglue",\n "❄️ungentlemanize",\n "❄️menacingly",\n "❄️heterophile",\n "❄️leoparde",\n "❄️Casearia",\n "❄️decorticate",\n "❄️neognathic",\n "❄️mentionable",\n "❄️tetraphenol",\n "❄️pseudonymal",\n "❄️dislegitimate",\n "❄️Discoidea",\n "❄️intitule",\n "❄️ionium",\n "❄️Lotuko",\n "❄️timbering",\n "❄️nonliquidating",\n "❄️oarialgia",\n "❄️Saccobranchus",\n "❄️reconnoiter",\n "❄️criminative",\n "❄️disintegratory",\n "❄️executer",\n "❄️Cylindrosporium",\n "❄️complimentation",\n "❄️Ixiama",\n "❄️Araceae",\n "❄️silaginoid",\n "❄️derencephalus",\n "❄️Lamiidae",\n "❄️marrowlike",\n "❄️ninepin",\n "❄️dynastid",\n "❄️lampfly",\n "❄️feint",\n "❄️trihemimer",\n "❄️semibarbarous",\n "❄️heresy",\n "❄️tritanope",\n "❄️indifferentist",\n "❄️confound",\n "❄️hyperbolaeon",\n "❄️planirostral",\n "❄️philosophunculist",\n "❄️existence",\n "❄️fretless",\n "❄️Leptandra",\n "❄️Amiranha",\n "❄️handgravure",\n "❄️gnash",\n "❄️unbelievability",\n "❄️orthotropic",\n "❄️Susumu",\n "❄️teleutospore",\n "❄️sleazy",\n "❄️shapeliness",\n "❄️hepatotomy",\n "❄️exclusivism",\n "❄️stifler",\n "❄️cunning",\n "❄️isocyanuric",\n "❄️pseudepigraphy",\n "❄️carpetbagger",\n "❄️respectiveness",\n "❄️Jussi",\n "❄️vasotomy",\n "❄️proctotomy",\n "❄️ovatotriangular",\n "❄️aesthetic",\n "❄️schizogamy",\n "❄️disengagement",\n "❄️foray",\n "❄️haplocaulescent",\n "❄️noncoherent",\n "❄️astrocyte",\n "❄️unreverberated",\n "❄️presenile",\n "❄️lanson",\n "❄️enkraal",\n "❄️contemplative",\n "❄️Syun",\n "❄️sartage",\n "❄️unforgot",\n "❄️wyde",\n "❄️homeotransplant",\n "❄️implicational",\n "❄️forerunnership",\n "❄️calcaneum",\n "❄️stomatodeum",\n "❄️pharmacopedia",\n "❄️preconcessive",\n "❄️trypanosomatic",\n "❄️intracollegiate",\n "❄️rampacious",\n "❄️secundipara",\n "❄️isomeric",\n "❄️treehair",\n "❄️pulmonal",\n "❄️uvate",\n "❄️dugway",\n "❄️glucofrangulin",\n "❄️unglory",\n "❄️Amandus",\n "❄️icterogenetic",\n "❄️quadrireme",\n "❄️Lagostomus",\n "❄️brakeroot",\n "❄️anthracemia",\n "❄️fluted",\n "❄️protoelastose",\n "❄️thro",\n "❄️pined",\n "❄️Saxicolinae",\n "❄️holidaymaking",\n "❄️strigil",\n "❄️uncurbed",\n "❄️starling",\n "❄️redeemeress",\n "❄️Liliaceae",\n "❄️imparsonee",\n "❄️obtusish",\n "❄️brushed",\n "❄️mesally",\n "❄️probosciformed",\n "❄️Bourbonesque",\n "❄️histological",\n "❄️caroba",\n "❄️digestion",\n "❄️Vindemiatrix",\n "❄️triactinal",\n "❄️tattling",\n "❄️arthrobacterium",\n "❄️unended",\n "❄️suspectfulness",\n "❄️movelessness",\n "❄️chartist",\n "❄️Corynebacterium",\n "❄️tercer",\n "❄️oversaturation",\n "❄️Congoleum",\n "❄️antiskeptical",\n "❄️sacral",\n "❄️equiradiate",\n "❄️whiskerage",\n "❄️panidiomorphic",\n "❄️unplanned",\n "❄️anilopyrine",\n "❄️Queres",\n "❄️tartronyl",\n "❄️Ing",\n "❄️notehead",\n "❄️finestiller",\n "❄️weekender",\n "❄️kittenhood",\n "❄️competitrix",\n "❄️premillenarian",\n "❄️convergescence",\n "❄️microcoleoptera",\n "❄️slirt",\n "❄️asteatosis",\n "❄️Gruidae",\n "❄️metastome",\n "❄️ambuscader",\n "❄️untugged",\n "❄️uneducated",\n "❄️redistill",\n "❄️rushlight",\n "❄️freakish",\n "❄️dosology",\n "❄️papyrine",\n "❄️iconologist",\n "❄️Bidpai",\n "❄️prophethood",\n "❄️pneumotropic",\n "❄️chloroformize",\n "❄️intemperance",\n "❄️spongiform",\n "❄️superindignant",\n "❄️divider",\n "❄️starlit",\n "❄️merchantish",\n "❄️indexless",\n "❄️unidentifiably",\n "❄️coumarone",\n "❄️nomism",\n "❄️diaphanous",\n "❄️salve",\n "❄️option",\n "❄️anallantoic",\n "❄️paint",\n "❄️thiofurfuran",\n "❄️baddeleyite",\n "❄️Donne",\n "❄️heterogenicity",\n "❄️decess",\n "❄️eschynite",\n "❄️mamma",\n "❄️unmonarchical",\n "❄️Archiplata",\n "❄️widdifow",\n "❄️apathic",\n "❄️overline",\n "❄️chaetophoraceous",\n "❄️creaky",\n "❄️trichosporange",\n "❄️uninterlined",\n "❄️cometwise",\n "❄️hermeneut",\n "❄️unbedraggled",\n "❄️tagged",\n "❄️Sminthurus",\n "❄️somniloquacious",\n "❄️aphasiac",\n "❄️Inoperculata",\n "❄️photoactivity",\n "❄️mobship",\n "❄️unblightedly",\n "❄️lievrite",\n "❄️Khoja",\n "❄️Falerian",\n "❄️milfoil",\n "❄️protectingly",\n "❄️householder",\n "❄️cathedra",\n "❄️calmingly",\n "❄️tordrillite",\n "❄️rearhorse",\n "❄️Leonard",\n "❄️maracock",\n "❄️youngish",\n "❄️kammererite",\n "❄️metanephric",\n "❄️Sageretia",\n "❄️diplococcoid",\n "❄️accelerative",\n "❄️choreal",\n "❄️metalogical",\n "❄️recombination",\n "❄️unimprison",\n "❄️invocation",\n "❄️syndetic",\n "❄️toadback",\n "❄️vaned",\n "❄️cupholder",\n "❄️metropolitanship",\n "❄️paramandelic",\n "❄️dermolysis",\n "❄️Sheriyat",\n "❄️rhabdus",\n "❄️seducee",\n "❄️encrinoid",\n "❄️unsuppliable",\n "❄️cololite",\n "❄️timesaver",\n "❄️preambulate",\n "❄️sampling",\n "❄️roaster",\n "❄️springald",\n "❄️densher",\n "❄️protraditional",\n "❄️naturalesque",\n "❄️Hydrodamalis",\n "❄️cytogenic",\n "❄️shortly",\n "❄️cryptogrammatical",\n "❄️squat",\n "❄️genual",\n "❄️backspier",\n "❄️solubleness",\n "❄️macroanalytical",\n "❄️overcovetousness",\n "❄️Natalie",\n "❄️cuprobismutite",\n "❄️phratriac",\n "❄️Montanize",\n "❄️hymnologist",\n "❄️karyomiton",\n "❄️podger",\n "❄️unofficiousness",\n "❄️antisplasher",\n "❄️supraclavicular",\n "❄️calidity",\n "❄️disembellish",\n "❄️antepredicament",\n "❄️recurvirostral",\n "❄️pulmonifer",\n "❄️coccidial",\n "❄️botonee",\n "❄️protoglobulose",\n "❄️isonym",\n "❄️myeloid",\n "❄️premiership",\n "❄️unmonopolize",\n "❄️unsesquipedalian",\n "❄️unfelicitously",\n "❄️theftbote",\n "❄️undauntable",\n "❄️lob",\n "❄️praenomen",\n "❄️underriver",\n "❄️gorfly",\n "❄️pluckage",\n "❄️radiovision",\n "❄️tyrantship",\n "❄️fraught",\n "❄️doppelkummel",\n "❄️rowan",\n "❄️allosyndetic",\n "❄️kinesiology",\n "❄️psychopath",\n "❄️arrent",\n "❄️amusively",\n "❄️preincorporation",\n "❄️Montargis",\n "❄️pentacron",\n "❄️neomedievalism",\n "❄️sima",\n "❄️lichenicolous",\n "❄️Ecclesiastes",\n "❄️woofed",\n "❄️cardinalist",\n "❄️sandaracin",\n "❄️gymnasial",\n "❄️lithoglyptics",\n "❄️centimeter",\n "❄️quadrupedous",\n "❄️phraseology",\n "❄️tumuli",\n "❄️ankylotomy",\n "❄️myrtol",\n "❄️cohibitive",\n "❄️lepospondylous",\n "❄️silvendy",\n "❄️inequipotential",\n "❄️entangle",\n "❄️raveling",\n "❄️Zeugobranchiata",\n "❄️devastating",\n "❄️grainage",\n "❄️amphisbaenian",\n "❄️blady",\n "❄️cirrose",\n "❄️proclericalism",\n "❄️governmentalist",\n "❄️carcinomorphic",\n "❄️nurtureship",\n "❄️clancular",\n "❄️unsteamed",\n "❄️discernibly",\n "❄️pleurogenic",\n "❄️impalpability",\n "❄️Azotobacterieae",\n "❄️sarcoplasmic",\n "❄️alternant",\n "❄️fitly",\n "❄️acrorrheuma",\n "❄️shrapnel",\n "❄️pastorize",\n "❄️gulflike",\n "❄️foreglow",\n "❄️unrelated",\n "❄️cirriped",\n "❄️cerviconasal",\n "❄️sexuale",\n "❄️pussyfooter",\n "❄️gadolinic",\n "❄️duplicature",\n "❄️codelinquency",\n "❄️trypanolysis",\n "❄️pathophobia",\n "❄️incapsulation",\n "❄️nonaerating",\n "❄️feldspar",\n "❄️diaphonic",\n "❄️epiglottic",\n "❄️depopulator",\n "❄️wisecracker",\n "❄️gravitational",\n "❄️kuba",\n "❄️lactesce",\n "❄️Toxotes",\n "❄️periomphalic",\n "❄️singstress",\n "❄️fannier",\n "❄️counterformula",\n "❄️Acemetae",\n "❄️repugnatorial",\n "❄️collimator",\n "❄️Acinetina",\n "❄️unpeace",\n "❄️drum",\n "❄️tetramorphic",\n "❄️descendentalism",\n "❄️cementer",\n "❄️supraloral",\n "❄️intercostal",\n "❄️Nipponize",\n "❄️negotiator",\n "❄️vacationless",\n "❄️synthol",\n "❄️fissureless",\n "❄️resoap",\n "❄️pachycarpous",\n "❄️reinspiration",\n "❄️misappropriation",\n "❄️disdiazo",\n "❄️unheatable",\n "❄️streng",\n "❄️Detroiter",\n "❄️infandous",\n "❄️loganiaceous",\n "❄️desugar",\n "❄️Matronalia",\n "❄️myxocystoma",\n "❄️Gandhiism",\n "❄️kiddier",\n "❄️relodge",\n "❄️counterreprisal",\n "❄️recentralize",\n "❄️foliously",\n "❄️reprinter",\n "❄️gender",\n "❄️edaciousness",\n "❄️chondriomite",\n "❄️concordant",\n "❄️stockrider",\n "❄️pedary",\n "❄️shikra",\n "❄️blameworthiness",\n "❄️vaccina",\n "❄️Thamnophilinae",\n "❄️wrongwise",\n "❄️unsuperannuated",\n "❄️convalescency",\n "❄️intransmutable",\n "❄️dropcloth",\n "❄️Ceriomyces",\n "❄️ponderal",\n "❄️unstentorian",\n "❄️mem",\n "❄️deceleration",\n "❄️ethionic",\n "❄️untopped",\n "❄️wetback",\n "❄️bebar",\n "❄️undecaying",\n "❄️shoreside",\n "❄️energize",\n "❄️presacral",\n "❄️undismay",\n "❄️agricolite",\n "❄️cowheart",\n "❄️hemibathybian",\n "❄️postexilian",\n "❄️Phacidiaceae",\n "❄️offing",\n "❄️redesignation",\n "❄️skeptically",\n "❄️physicianless",\n "❄️bronchopathy",\n "❄️marabuto",\n "❄️proprietory",\n "❄️unobtruded",\n "❄️funmaker",\n "❄️plateresque",\n "❄️preadventure",\n "❄️beseeching",\n "❄️cowpath",\n "❄️pachycephalia",\n "❄️arthresthesia",\n "❄️supari",\n "❄️lengthily",\n "❄️Nepa",\n "❄️liberation",\n "❄️nigrify",\n "❄️belfry",\n "❄️entoolitic",\n "❄️bazoo",\n "❄️pentachromic",\n "❄️distinguishable",\n "❄️slideable",\n "❄️galvanoscope",\n "❄️remanage",\n "❄️cetene",\n "❄️bocardo",\n "❄️consummation",\n "❄️boycottism",\n "❄️perplexity",\n "❄️astay",\n "❄️Gaetuli",\n "❄️periplastic",\n "❄️consolidator",\n "❄️sluggarding",\n "❄️coracoscapular",\n "❄️anangioid",\n "❄️oxygenizer",\n "❄️Hunanese",\n "❄️seminary",\n "❄️periplast",\n "❄️Corylus",\n "❄️unoriginativeness",\n "❄️persecutee",\n "❄️tweaker",\n "❄️silliness",\n "❄️Dabitis",\n "❄️facetiousness",\n "❄️thymy",\n "❄️nonimperial",\n "❄️mesoblastema",\n "❄️turbiniform",\n "❄️churchway",\n "❄️cooing",\n "❄️frithbot",\n "❄️concomitantly",\n "❄️stalwartize",\n "❄️clingfish",\n "❄️hardmouthed",\n "❄️parallelepipedonal",\n "❄️coracoacromial",\n "❄️factuality",\n "❄️curtilage",\n "❄️arachnoidean",\n "❄️semiaridity",\n "❄️phytobacteriology",\n "❄️premastery",\n "❄️hyperpurist",\n "❄️mobed",\n "❄️opportunistic",\n "❄️acclimature",\n "❄️outdistance",\n "❄️sophister",\n "❄️condonement",\n "❄️oxygenerator",\n "❄️acetonic",\n "❄️emanatory",\n "❄️periphlebitis",\n "❄️nonsociety",\n "❄️spectroradiometric",\n "❄️superaverage",\n "❄️cleanness",\n "❄️posteroventral",\n "❄️unadvised",\n "❄️unmistakedly",\n "❄️pimgenet",\n "❄️auresca",\n "❄️overimitate",\n "❄️dipnoan",\n "❄️chromoxylograph",\n "❄️triakistetrahedron",\n "❄️Suessiones",\n "❄️uncopiable",\n "❄️oligomenorrhea",\n "❄️fribbling",\n "❄️worriable",\n "❄️flot",\n "❄️ornithotrophy",\n "❄️phytoteratology",\n "❄️setup",\n "❄️lanneret",\n "❄️unbraceleted",\n "❄️gudemother",\n "❄️Spica",\n "❄️unconsolatory",\n "❄️recorruption",\n "❄️premenstrual",\n "❄️subretinal",\n "❄️millennialist",\n "❄️subjectibility",\n "❄️rewardproof",\n "❄️counterflight",\n "❄️pilomotor",\n "❄️carpetbaggery",\n "❄️macrodiagonal",\n "❄️slim",\n "❄️indiscernible",\n "❄️cuckoo",\n "❄️moted",\n "❄️controllingly",\n "❄️gynecopathy",\n "❄️porrectus",\n "❄️wanworth",\n "❄️lutfisk",\n "❄️semiprivate",\n "❄️philadelphy",\n "❄️abdominothoracic",\n "❄️coxcomb",\n "❄️dambrod",\n "❄️Metanemertini",\n "❄️balminess",\n "❄️homotypy",\n "❄️waremaker",\n "❄️absurdity",\n "❄️gimcrack",\n "❄️asquat",\n "❄️suitable",\n "❄️perimorphous",\n "❄️kitchenwards",\n "❄️pielum",\n "❄️salloo",\n "❄️paleontologic",\n "❄️Olson",\n "❄️Tellinidae",\n "❄️ferryman",\n "❄️peptonoid",\n "❄️Bopyridae",\n "❄️fallacy",\n "❄️ictuate",\n "❄️aguinaldo",\n "❄️rhyodacite",\n "❄️Ligydidae",\n "❄️galvanometric",\n "❄️acquisitor",\n "❄️muscology",\n "❄️hemikaryon",\n "❄️ethnobotanic",\n "❄️postganglionic",\n "❄️rudimentarily",\n "❄️replenish",\n "❄️phyllorhine",\n "❄️popgunnery",\n "❄️summar",\n "❄️quodlibetary",\n "❄️xanthochromia",\n "❄️autosymbolically",\n "❄️preloreal",\n "❄️extent",\n "❄️strawberry",\n "❄️immortalness",\n "❄️colicwort",\n "❄️frisca",\n "❄️electiveness",\n "❄️heartbroken",\n "❄️affrightingly",\n "❄️reconfiscation",\n "❄️jacchus",\n "❄️imponderably",\n "❄️semantics",\n "❄️beennut",\n "❄️paleometeorological",\n "❄️becost",\n "❄️timberwright",\n "❄️resuppose",\n "❄️syncategorematical",\n "❄️cytolymph",\n "❄️steinbok",\n "❄️explantation",\n "❄️hyperelliptic",\n "❄️antescript",\n "❄️blowdown",\n "❄️antinomical",\n "❄️caravanserai",\n "❄️unweariedly",\n "❄️isonymic",\n "❄️keratoplasty",\n "❄️vipery",\n "❄️parepigastric",\n "❄️endolymphatic",\n "❄️Londonese",\n "❄️necrotomy",\n "❄️angelship",\n "❄️Schizogregarinida",\n "❄️steeplebush",\n "❄️sparaxis",\n "❄️connectedness",\n "❄️tolerance",\n "❄️impingent",\n "❄️agglutinin",\n "❄️reviver",\n "❄️hieroglyphical",\n "❄️dialogize",\n "❄️coestate",\n "❄️declamatory",\n "❄️ventilation",\n "❄️tauromachy",\n "❄️cotransubstantiate",\n "❄️pome",\n "❄️underseas",\n "❄️triquadrantal",\n "❄️preconfinemnt",\n "❄️electroindustrial",\n "❄️selachostomous",\n "❄️nongolfer",\n "❄️mesalike",\n "❄️hamartiology",\n "❄️ganglioblast",\n "❄️unsuccessive",\n "❄️yallow",\n "❄️bacchanalianly",\n "❄️platydactyl",\n "❄️Bucephala",\n "❄️ultraurgent",\n "❄️penalist",\n "❄️catamenial",\n "❄️lynnhaven",\n "❄️unrelevant",\n "❄️lunkhead",\n "❄️metropolitan",\n "❄️hydro",\n "❄️outsoar",\n "❄️vernant",\n "❄️interlanguage",\n "❄️catarrhal",\n "❄️Ionicize",\n "❄️keelless",\n "❄️myomantic",\n "❄️booker",\n "❄️Xanthomonas",\n "❄️unimpeded",\n "❄️overfeminize",\n "❄️speronaro",\n "❄️diaconia",\n "❄️overholiness",\n "❄️liquefacient",\n "❄️Spartium",\n "❄️haggly",\n "❄️albumose",\n "❄️nonnecessary",\n "❄️sulcalization",\n "❄️decapitate",\n "❄️cellated",\n "❄️unguirostral",\n "❄️trichiurid",\n "❄️loveproof",\n "❄️amakebe",\n "❄️screet",\n "❄️arsenoferratin",\n "❄️unfrizz",\n "❄️undiscoverable",\n "❄️procollectivistic",\n "❄️tractile",\n "❄️Winona",\n "❄️dermostosis",\n "❄️eliminant",\n "❄️scomberoid",\n "❄️tensile",\n "❄️typesetting",\n "❄️xylic",\n "❄️dermatopathology",\n "❄️cycloplegic",\n "❄️revocable",\n "❄️fissate",\n "❄️afterplay",\n "❄️screwship",\n "❄️microerg",\n "❄️bentonite",\n "❄️stagecoaching",\n "❄️beglerbeglic",\n "❄️overcharitably",\n "❄️Plotinism",\n "❄️Veddoid",\n "❄️disequalize",\n "❄️cytoproct",\n "❄️trophophore",\n "❄️antidote",\n "❄️allerion",\n "❄️famous",\n "❄️convey",\n "❄️postotic",\n "❄️rapillo",\n "❄️cilectomy",\n "❄️penkeeper",\n "❄️patronym",\n "❄️bravely",\n "❄️ureteropyelitis",\n "❄️Hildebrandine",\n "❄️missileproof",\n "❄️Conularia",\n "❄️deadening",\n "❄️Conrad",\n "❄️pseudochylous",\n "❄️typologically",\n "❄️strummer",\n "❄️luxuriousness",\n "❄️resublimation",\n "❄️glossiness",\n "❄️hydrocauline",\n "❄️anaglyph",\n "❄️personifiable",\n "❄️seniority",\n "❄️formulator",\n "❄️datiscaceous",\n "❄️hydracrylate",\n "❄️Tyranni",\n "❄️Crawthumper",\n "❄️overprove",\n "❄️masher",\n "❄️dissonance",\n "❄️Serpentinian",\n "❄️malachite",\n "❄️interestless",\n "❄️stchi",\n "❄️ogum",\n "❄️polyspermic",\n "❄️archegoniate",\n "❄️precogitation",\n "❄️Alkaphrah",\n "❄️craggily",\n "❄️delightfulness",\n "❄️bioplast",\n "❄️diplocaulescent",\n "❄️neverland",\n "❄️interspheral",\n "❄️chlorhydric",\n "❄️forsakenly",\n "❄️scandium",\n "❄️detubation",\n "❄️telega",\n "❄️Valeriana",\n "❄️centraxonial",\n "❄️anabolite",\n "❄️neger",\n "❄️miscellanea",\n "❄️whalebacker",\n "❄️stylidiaceous",\n "❄️unpropelled",\n "❄️Kennedya",\n "❄️Jacksonite",\n "❄️ghoulish",\n "❄️Dendrocalamus",\n "❄️paynimhood",\n "❄️rappist",\n "❄️unluffed",\n "❄️falling",\n "❄️Lyctus",\n "❄️uncrown",\n "❄️warmly",\n "❄️pneumatism",\n "❄️Morisonian",\n "❄️notate",\n "❄️isoagglutinin",\n "❄️Pelidnota",\n "❄️previsit",\n "❄️contradistinctly",\n "❄️utter",\n "❄️porometer",\n "❄️gie",\n "❄️germanization",\n "❄️betwixt",\n "❄️prenephritic",\n "❄️underpier",\n "❄️Eleutheria",\n "❄️ruthenious",\n "❄️convertor",\n "❄️antisepsin",\n "❄️winterage",\n "❄️tetramethylammonium",\n "❄️Rockaway",\n "❄️Penaea",\n "❄️prelatehood",\n "❄️brisket",\n "❄️unwishful",\n "❄️Minahassa",\n "❄️Briareus",\n "❄️semiaxis",\n "❄️disintegrant",\n "❄️peastick",\n "❄️iatromechanical",\n "❄️fastus",\n "❄️thymectomy",\n "❄️ladyless",\n "❄️unpreened",\n "❄️overflutter",\n "❄️sicker",\n "❄️apsidally",\n "❄️thiazine",\n "❄️guideway",\n "❄️pausation",\n "❄️tellinoid",\n "❄️abrogative",\n "❄️foraminulate",\n "❄️omphalos",\n "❄️Monorhina",\n "❄️polymyarian",\n "❄️unhelpful",\n "❄️newslessness",\n "❄️oryctognosy",\n "❄️octoradial",\n "❄️doxology",\n "❄️arrhythmy",\n "❄️gugal",\n "❄️mesityl",\n "❄️hexaplaric",\n "❄️Cabirian",\n "❄️hordeiform",\n "❄️eddyroot",\n "❄️internarial",\n "❄️deservingness",\n "❄️jawbation",\n "❄️orographically",\n "❄️semiprecious",\n "❄️seasick",\n "❄️thermically",\n "❄️grew",\n "❄️tamability",\n "❄️egotistically",\n "❄️fip",\n "❄️preabsorbent",\n "❄️leptochroa",\n "❄️ethnobotany",\n "❄️podolite",\n "❄️egoistic",\n "❄️semitropical",\n "❄️cero",\n "❄️spinelessness",\n "❄️onshore",\n "❄️omlah",\n "❄️tintinnabulist",\n "❄️machila",\n "❄️entomotomy",\n "❄️nubile",\n "❄️nonscholastic",\n "❄️burnt",\n "❄️Alea",\n "❄️befume",\n "❄️doctorless",\n "❄️Napoleonic",\n "❄️scenting",\n "❄️apokreos",\n "❄️cresylene",\n "❄️paramide",\n "❄️rattery",\n "❄️disinterested",\n "❄️idiopathetic",\n "❄️negatory",\n "❄️fervid",\n "❄️quintato",\n "❄️untricked",\n "❄️Metrosideros",\n "❄️mescaline",\n "❄️midverse",\n "❄️Musophagidae",\n "❄️fictionary",\n "❄️branchiostegous",\n "❄️yoker",\n "❄️residuum",\n "❄️culmigenous",\n "❄️fleam",\n "❄️suffragism",\n "❄️Anacreon",\n "❄️sarcodous",\n "❄️parodistic",\n "❄️writmaking",\n "❄️conversationism",\n "❄️retroposed",\n "❄️tornillo",\n "❄️presuspect",\n "❄️didymous",\n "❄️Saumur",\n "❄️spicing",\n "❄️drawbridge",\n "❄️cantor",\n "❄️incumbrancer",\n "❄️heterospory",\n "❄️Turkeydom",\n "❄️anteprandial",\n "❄️neighborship",\n "❄️thatchless",\n "❄️drepanoid",\n "❄️lusher",\n "❄️paling",\n "❄️ecthlipsis",\n "❄️heredosyphilitic",\n "❄️although",\n "❄️garetta",\n "❄️temporarily",\n "❄️Monotropa",\n "❄️proglottic",\n "❄️calyptro",\n "❄️persiflage",\n "❄️degradable",\n "❄️paraspecific",\n "❄️undecorative",\n "❄️Pholas",\n "❄️myelon",\n "❄️resteal",\n "❄️quadrantly",\n "❄️scrimped",\n "❄️airer",\n "❄️deviless",\n "❄️caliciform",\n "❄️Sefekhet",\n "❄️shastaite",\n "❄️togate",\n "❄️macrostructure",\n "❄️bipyramid",\n "❄️wey",\n "❄️didynamy",\n "❄️knacker",\n "❄️swage",\n "❄️supermanism",\n "❄️epitheton",\n "❄️overpresumptuous"\n ]\n\npublic func run_SortStringsUnicode(_ n: Int) {\n for _ in 1...n {\n benchSortStrings(unicodeWords)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SortStrings.swift | cpp_apple_swift_benchmark_single-source_SortStrings.swift | Swift | 39,372 | 0.95 | 0.002427 | 0.006823 | node-utils | 107 | 2024-06-03T01:55:38.889748 | GPL-3.0 | false | f7176212fb946e21b7a8736c4897b8ba |
//===----------------------------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "StackPromo",\n runFunction: run_StackPromo,\n tags: [.regression, .cpubench],\n legacyFactor: 100)\n\nprotocol Proto {\n func at() -> Int\n}\n\n@inline(never)\nfunc testStackAllocation(_ p: Proto) -> Int {\n var a = [p, p, p]\n var b = 0\n a.withUnsafeMutableBufferPointer {\n let array = $0\n for i in 0..<array.count {\n b += array[i].at()\n }\n }\n return b\n}\n\nclass Foo : Proto {\n init() {}\n func at() -> Int{\n return 1\n }\n}\n\n@inline(never)\nfunc work(_ f: Foo) -> Int {\n var r = 0\n for _ in 0..<1_000 {\n r += testStackAllocation(f)\n }\n return r\n}\n\npublic func run_StackPromo(_ n: Int) {\n let foo = Foo()\n var r = 0\n for i in 0..<n {\n if i % 2 == 0 {\n r += work(foo)\n } else {\n r -= work(foo)\n }\n }\n blackHole(r)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StackPromo.swift | cpp_apple_swift_benchmark_single-source_StackPromo.swift | Swift | 1,355 | 0.95 | 0.107692 | 0.186441 | python-kit | 453 | 2024-08-29T03:07:01.421130 | GPL-3.0 | false | e89d1fd85c806617e4239fa4c7ff6f32 |
//===--- StaticArray.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// We use this test to benchmark the compile time and analyze the code\n// generation of struct initializers.\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "StaticArray",\n runFunction: run_StaticArray,\n tags: [.validation, .api, .Array]),\n]\n\nprotocol StaticArrayProtocol {\n associatedtype ElemTy\n init(_ defaultValue : ElemTy)\n func get(_ idx : Int) -> ElemTy\n mutating func set(_ idx : Int,_ val : ElemTy)\n func count() -> Int\n}\n\nstruct A0<ElemTy> : StaticArrayProtocol {\n init(_ defaultValue : ElemTy) { x = defaultValue }\n var x : ElemTy\n func get(_ idx : Int) -> ElemTy { if idx == 0 { return x } else { fatalError("oob"); } }\n mutating func set(_ idx : Int,_ val : ElemTy) { if idx == 0 { x = val }}\n func count() -> Int { return 1}\n}\n\nstruct A2X<T : StaticArrayProtocol> : StaticArrayProtocol {\n init(_ defaultValue : T.ElemTy) { lower = T(defaultValue); upper = T(defaultValue) }\n var lower : T\n var upper : T\n func get(_ idx: Int) -> T.ElemTy { let size = lower.count(); if idx < size { return lower.get(idx) } else { return upper.get(idx - size) }}\n mutating func set(_ idx: Int,_ val : T.ElemTy) {let size = lower.count(); if idx < size { return lower.set(idx, val) } else { return upper.set(idx - size, val) }}\n func count() -> Int { return upper.count() + lower.count() }\n}\n\nstruct StaticArray<\n T : StaticArrayProtocol\n> : StaticArrayProtocol, RandomAccessCollection, MutableCollection { \n init(_ defaultValue : T.ElemTy) { values = T(defaultValue) }\n var values : T\n func get(_ idx: Int) -> T.ElemTy { return values.get(idx) }\n mutating func set(_ idx: Int,_ val : T.ElemTy) { return values.set(idx, val) }\n func count() -> Int { return values.count() }\n\n typealias Index = Int\n let startIndex: Int = 0\n var endIndex: Int { return count()}\n\n subscript(idx: Int) -> T.ElemTy {\n get {\n return get(idx)\n }\n set(val) {\n set(idx, val)\n }\n }\n\n typealias Iterator = IndexingIterator<StaticArray>\n\n subscript(bounds: Range<Index>) -> StaticArray<T> {\n get { fatalError() }\n set { fatalError() }\n }\n}\n\ntypealias SA2Int = StaticArray<A0<Int>>\ntypealias SA4Int = StaticArray<A2X<A0<Int>>>\ntypealias SA8Int = StaticArray<A2X<A2X<A0<Int>>>>\ntypealias SA16Int = StaticArray<A2X<A2X<A2X<A0<Int>>>>>\ntypealias SA32Int = StaticArray<A2X<A2X<A2X<A2X<A0<Int>>>>>>\ntypealias SA64Int = StaticArray<A2X<A2X<A2X<A2X<A2X<A0<Int>>>>>>>\ntypealias SA128Int = StaticArray<A2X<A2X<A2X<A2X<A2X<A2X<A0<Int>>>>>>>>\n\n// Make sure the optimizer does not optimize the compute away.\n@inline(never)\npublic func sink(_ value: Int) { if getFalse() { print(value) }}\n\n\n@inline(never)\npublic func run_StaticArray(_ n: Int) {\n\n for _ in 1...n {\n var staticArray = SA128Int(0)\n for i in 0..<staticArray.count() { staticArray[i] = i ^ 123 }\n staticArray.sort()\n sink(staticArray[0])\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StaticArray.swift | cpp_apple_swift_benchmark_single-source_StaticArray.swift | Swift | 3,475 | 0.95 | 0.087379 | 0.181818 | python-kit | 122 | 2023-09-17T04:24:06.056850 | Apache-2.0 | false | fad629783b5598d0cd3f1080d9d332b9 |
//===--- StrComplexWalk.swift ---------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "StrComplexWalk",\n runFunction: run_StrComplexWalk,\n tags: [.validation, .api, .String],\n legacyFactor: 10)\n\n@inline(never)\npublic func run_StrComplexWalk(_ n: Int) {\n let s = "निरन्तरान्धकारिता-दिगन्तर-कन्दलदमन्द-सुधारस-बिन्दु-सान्द्रतर-घनाघन-वृन्द-सन्देहकर-स्यन्दमान-मकरन्द-बिन्दु-बन्धुरतर-माकन्द-तरु-कुल-तल्प-कल्प-मृदुल-सिकता-जाल-जटिल-मूल-तल-मरुवक-मिलदलघु-लघु-लय-कलित-रमणीय-पानीय-शालिका-बालिका-करार-विन्द-गलन्तिका-गलदेला-लवङ्ग-पाटल-घनसार-कस्तूरिकातिसौरभ-मेदुर-लघुतर-मधुर-शीतलतर-सलिलधारा-निराकरिष्णु-तदीय-विमल-विलोचन-मयूख-रेखापसारित-पिपासायास-पथिक-लोकान्"\n let ref_result = 379\n for _ in 1...200*n {\n var count = 0\n for _ in s.unicodeScalars {\n count += 1\n }\n check(count == ref_result)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StrComplexWalk.swift | cpp_apple_swift_benchmark_single-source_StrComplexWalk.swift | Swift | 1,964 | 0.95 | 0.121212 | 0.366667 | node-utils | 533 | 2024-02-10T07:35:14.551027 | GPL-3.0 | false | ecd6c08ade810a715b5100f2592ec695 |
//===--- StringBuilder.swift ----------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "StringAdder",\n runFunction: run_StringAdder,\n tags: [.validation, .api, .String]),\n BenchmarkInfo(\n name: "StringBuilder",\n runFunction: run_StringBuilder,\n tags: [.validation, .api, .String]),\n BenchmarkInfo(\n name: "StringBuilderSmallReservingCapacity",\n runFunction: run_StringBuilderSmallReservingCapacity,\n tags: [.validation, .api, .String]),\n BenchmarkInfo(\n name: "StringUTF16Builder",\n runFunction: run_StringUTF16Builder,\n tags: [.validation, .api, .String],\n legacyFactor: 10),\n BenchmarkInfo(\n name: "StringUTF16SubstringBuilder",\n runFunction: run_StringUTF16SubstringBuilder,\n tags: [.validation, .api, .String],\n legacyFactor: 10),\n BenchmarkInfo(\n name: "StringBuilderLong",\n runFunction: run_StringBuilderLong,\n tags: [.validation, .api, .String],\n legacyFactor: 10),\n BenchmarkInfo(\n name: "StringBuilderWithLongSubstring",\n runFunction: run_StringBuilderWithLongSubstring,\n tags: [.validation, .api, .String],\n legacyFactor: 10),\n BenchmarkInfo(\n name: "StringWordBuilder",\n runFunction: run_StringWordBuilder,\n tags: [.validation, .api, .String],\n legacyFactor: 10),\n BenchmarkInfo(\n name: "StringWordBuilderReservingCapacity",\n runFunction: run_StringWordBuilderReservingCapacity,\n tags: [.validation, .api, .String],\n legacyFactor: 10),\n]\n\n@inline(never)\nfunc buildString(_ i: String, reservingCapacity: Bool = false) -> String {\n var sb = getString(i)\n if reservingCapacity {\n sb.reserveCapacity(10)\n }\n for str in ["b","c","d","pizza"] {\n sb += str\n }\n return sb\n}\n\n@inline(never)\npublic func run_StringBuilder(_ n: Int) {\n for _ in 1...5000*n {\n blackHole(buildString("a"))\n }\n}\n\n@inline(never)\npublic func run_StringBuilderSmallReservingCapacity(_ n: Int) {\n for _ in 1...5000*n {\n blackHole(buildString("a", reservingCapacity: true))\n }\n}\n\n@inline(never)\nfunc addString(_ i: String) -> String {\n let s = getString(i) + "b" + "c" + "d" + "pizza"\n return s\n}\n\n@inline(never)\npublic func run_StringAdder(_ n: Int) {\n for _ in 1...5000*n {\n blackHole(addString("a"))\n }\n}\n\n@inline(never)\nfunc buildStringUTF16(_ i: String) -> String {\n var sb = getString(i)\n for str in ["🎉","c","d","pizza"] {\n sb += str\n }\n return sb\n}\n\n@inline(never)\nfunc buildStringFromSmallSubstrings(_ i: String) -> String {\n var sb = getString(i)\n for str in ["_🎉","cd","de","pizza"] {\n sb += str.dropFirst()\n }\n return sb\n}\n\n@inline(never)\npublic func run_StringUTF16Builder(_ n: Int) {\n for _ in 1...500*n {\n blackHole(buildStringUTF16("a"))\n }\n}\n\n@inline(never)\npublic func run_StringUTF16SubstringBuilder(_ n: Int) {\n for _ in 1...500*n {\n blackHole(buildStringFromSmallSubstrings("a"))\n }\n}\n\nfunc getLongString() -> String {\n let long = """\n Swift is a multi-paradigm, compiled programming language created for\n iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is\n designed to work with Apple's Cocoa and Cocoa Touch frameworks and the\n large body of existing Objective-C code written for Apple products. Swift\n is intended to be more resilient to erroneous code (\"safer\") than\n Objective-C and also more concise. It is built with the LLVM compiler\n framework included in Xcode 6 and later and uses the Objective-C runtime,\n which allows C, Objective-C, C++ and Swift code to run within a single\n program.\n """\n return getString(long)\n}\n\n@inline(never)\nfunc buildStringLong(_ i: String) -> String {\n var sb = getString(i)\n sb += getLongString()\n return sb\n}\n\n@inline(never)\nfunc buildStringWithLongSubstring(_ i: String) -> String {\n var sb = getString(i)\n sb += getLongString().dropFirst()\n return sb\n}\n\n@inline(never)\npublic func run_StringBuilderLong(_ n: Int) {\n for _ in 1...500*n {\n blackHole(buildStringLong("👻"))\n }\n}\n\n@inline(never)\npublic func run_StringBuilderWithLongSubstring(_ n: Int) {\n for _ in 1...500*n {\n blackHole(buildStringWithLongSubstring("👻"))\n }\n}\n\n@inline(never)\nfunc buildString(\n word: String,\n count: Int,\n reservingCapacity: Bool\n) -> String {\n let word = getString(word)\n var sb = ""\n if reservingCapacity {\n sb.reserveCapacity(count * word.unicodeScalars.count)\n }\n for _ in 0 ..< count {\n sb += word\n }\n return sb\n}\n\n@inline(never)\npublic func run_StringWordBuilder(_ n: Int) {\n for _ in 1...n {\n blackHole(buildString(\n word: "bumfuzzle", count: 5_000, reservingCapacity: false))\n }\n}\n\n@inline(never)\npublic func run_StringWordBuilderReservingCapacity(_ n: Int) {\n for _ in 1...n {\n blackHole(buildString(\n word: "bumfuzzle", count: 5_000, reservingCapacity: true))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringBuilder.swift | cpp_apple_swift_benchmark_single-source_StringBuilder.swift | Swift | 5,282 | 0.95 | 0.092683 | 0.05914 | react-lib | 499 | 2025-05-12T08:24:52.327924 | BSD-3-Clause | false | 00b87c30ec6725d6b9d76f1dec0712c5 |
//===--- StringComparison.swift -------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to StringComparison.swift.gyb and run\n// scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\n//\n// Test String iteration performance over a variety of workloads, languages,\n// and symbols.\n//\n\nimport TestsUtils\n\nextension String {\n func lines() -> [String] {\n return self.split(separator: "\n").map { String($0) }\n }\n}\npublic let benchmarks: [BenchmarkInfo] = [\n BenchmarkInfo(\n name: "StringComparison_ascii",\n runFunction: run_StringComparison_ascii,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_ascii) }\n ),\n BenchmarkInfo(\n name: "StringComparison_latin1",\n runFunction: run_StringComparison_latin1,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_latin1) },\n legacyFactor: 2\n ),\n BenchmarkInfo(\n name: "StringComparison_fastPrenormal",\n runFunction: run_StringComparison_fastPrenormal,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_fastPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "StringComparison_slowerPrenormal",\n runFunction: run_StringComparison_slowerPrenormal,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_slowerPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "StringComparison_nonBMPSlowestPrenormal",\n runFunction: run_StringComparison_nonBMPSlowestPrenormal,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_nonBMPSlowestPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "StringComparison_emoji",\n runFunction: run_StringComparison_emoji,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_emoji) },\n legacyFactor: 4\n ),\n BenchmarkInfo(\n name: "StringComparison_abnormal",\n runFunction: run_StringComparison_abnormal,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_abnormal) },\n legacyFactor: 20\n ),\n BenchmarkInfo(\n name: "StringComparison_zalgo",\n runFunction: run_StringComparison_zalgo,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_zalgo) },\n legacyFactor: 25\n ),\n BenchmarkInfo(\n name: "StringComparison_longSharedPrefix",\n runFunction: run_StringComparison_longSharedPrefix,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_longSharedPrefix) }\n ),\n\n BenchmarkInfo(\n name: "StringHashing_ascii",\n runFunction: run_StringHashing_ascii,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_ascii) }\n ),\n BenchmarkInfo(\n name: "StringHashing_latin1",\n runFunction: run_StringHashing_latin1,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_latin1) },\n legacyFactor: 2\n ),\n BenchmarkInfo(\n name: "StringHashing_fastPrenormal",\n runFunction: run_StringHashing_fastPrenormal,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_fastPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "StringHashing_slowerPrenormal",\n runFunction: run_StringHashing_slowerPrenormal,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_slowerPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "StringHashing_nonBMPSlowestPrenormal",\n runFunction: run_StringHashing_nonBMPSlowestPrenormal,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_nonBMPSlowestPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "StringHashing_emoji",\n runFunction: run_StringHashing_emoji,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_emoji) },\n legacyFactor: 4\n ),\n BenchmarkInfo(\n name: "StringHashing_abnormal",\n runFunction: run_StringHashing_abnormal,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_abnormal) },\n legacyFactor: 20\n ),\n BenchmarkInfo(\n name: "StringHashing_zalgo",\n runFunction: run_StringHashing_zalgo,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(workload_zalgo) },\n legacyFactor: 25\n ),\n\n BenchmarkInfo(\n name: "NormalizedIterator_ascii",\n runFunction: run_StringNormalization_ascii,\n tags: [.validation, .String],\n setUpFunction: { blackHole(workload_ascii) }\n ),\n BenchmarkInfo(\n name: "NormalizedIterator_latin1",\n runFunction: run_StringNormalization_latin1,\n tags: [.validation, .String],\n setUpFunction: { blackHole(workload_latin1) },\n legacyFactor: 2\n ),\n BenchmarkInfo(\n name: "NormalizedIterator_fastPrenormal",\n runFunction: run_StringNormalization_fastPrenormal,\n tags: [.validation, .String],\n setUpFunction: { blackHole(workload_fastPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "NormalizedIterator_slowerPrenormal",\n runFunction: run_StringNormalization_slowerPrenormal,\n tags: [.validation, .String],\n setUpFunction: { blackHole(workload_slowerPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "NormalizedIterator_nonBMPSlowestPrenormal",\n runFunction: run_StringNormalization_nonBMPSlowestPrenormal,\n tags: [.validation, .String],\n setUpFunction: { blackHole(workload_nonBMPSlowestPrenormal) },\n legacyFactor: 10\n ),\n BenchmarkInfo(\n name: "NormalizedIterator_emoji",\n runFunction: run_StringNormalization_emoji,\n tags: [.validation, .String],\n setUpFunction: { blackHole(workload_emoji) },\n legacyFactor: 4\n ),\n BenchmarkInfo(\n name: "NormalizedIterator_abnormal",\n runFunction: run_StringNormalization_abnormal,\n tags: [.validation, .String],\n setUpFunction: { blackHole(workload_abnormal) },\n legacyFactor: 20\n ),\n BenchmarkInfo(\n name: "NormalizedIterator_zalgo",\n runFunction: run_StringNormalization_zalgo,\n tags: [.validation, .String],\n setUpFunction: { blackHole(workload_zalgo) },\n legacyFactor: 25\n ),\n]\n\nlet workload_ascii: Workload! = Workload.ascii\n\nlet workload_latin1: Workload! = Workload.latin1\n\nlet workload_fastPrenormal: Workload! = Workload.fastPrenormal\n\nlet workload_slowerPrenormal: Workload! = Workload.slowerPrenormal\n\nlet workload_nonBMPSlowestPrenormal: Workload! = Workload.nonBMPSlowestPrenormal\n\nlet workload_emoji: Workload! = Workload.emoji\n\nlet workload_abnormal: Workload! = Workload.abnormal\n\nlet workload_zalgo: Workload! = Workload.zalgo\n\nlet workload_longSharedPrefix: Workload! = Workload.longSharedPrefix\n\n\n@inline(never)\npublic func run_StringComparison_ascii(_ n: Int) {\n let workload: Workload = workload_ascii\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringComparison_latin1(_ n: Int) {\n let workload: Workload = workload_latin1\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringComparison_fastPrenormal(_ n: Int) {\n let workload: Workload = workload_fastPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringComparison_slowerPrenormal(_ n: Int) {\n let workload: Workload = workload_slowerPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringComparison_nonBMPSlowestPrenormal(_ n: Int) {\n let workload: Workload = workload_nonBMPSlowestPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringComparison_emoji(_ n: Int) {\n let workload: Workload = workload_emoji\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringComparison_abnormal(_ n: Int) {\n let workload: Workload = workload_abnormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringComparison_zalgo(_ n: Int) {\n let workload: Workload = workload_zalgo\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringComparison_longSharedPrefix(_ n: Int) {\n let workload: Workload = workload_longSharedPrefix\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for s1 in payload {\n for s2 in payload {\n blackHole(s1 < s2)\n }\n }\n }\n}\n\n\n@inline(never)\npublic func run_StringHashing_ascii(_ n: Int) {\n let workload: Workload = Workload.ascii\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n blackHole(str.hashValue)\n }\n }\n}\n\n@inline(never)\npublic func run_StringHashing_latin1(_ n: Int) {\n let workload: Workload = Workload.latin1\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n blackHole(str.hashValue)\n }\n }\n}\n\n@inline(never)\npublic func run_StringHashing_fastPrenormal(_ n: Int) {\n let workload: Workload = Workload.fastPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n blackHole(str.hashValue)\n }\n }\n}\n\n@inline(never)\npublic func run_StringHashing_slowerPrenormal(_ n: Int) {\n let workload: Workload = Workload.slowerPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n blackHole(str.hashValue)\n }\n }\n}\n\n@inline(never)\npublic func run_StringHashing_nonBMPSlowestPrenormal(_ n: Int) {\n let workload: Workload = Workload.nonBMPSlowestPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n blackHole(str.hashValue)\n }\n }\n}\n\n@inline(never)\npublic func run_StringHashing_emoji(_ n: Int) {\n let workload: Workload = Workload.emoji\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n blackHole(str.hashValue)\n }\n }\n}\n\n@inline(never)\npublic func run_StringHashing_abnormal(_ n: Int) {\n let workload: Workload = Workload.abnormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n blackHole(str.hashValue)\n }\n }\n}\n\n@inline(never)\npublic func run_StringHashing_zalgo(_ n: Int) {\n let workload: Workload = Workload.zalgo\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n blackHole(str.hashValue)\n }\n }\n}\n\n\n@inline(never)\npublic func run_StringNormalization_ascii(_ n: Int) {\n let workload: Workload = Workload.ascii\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n str._withNFCCodeUnits { cu in\n blackHole(cu)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringNormalization_latin1(_ n: Int) {\n let workload: Workload = Workload.latin1\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n str._withNFCCodeUnits { cu in\n blackHole(cu)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringNormalization_fastPrenormal(_ n: Int) {\n let workload: Workload = Workload.fastPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n str._withNFCCodeUnits { cu in\n blackHole(cu)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringNormalization_slowerPrenormal(_ n: Int) {\n let workload: Workload = Workload.slowerPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n str._withNFCCodeUnits { cu in\n blackHole(cu)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringNormalization_nonBMPSlowestPrenormal(_ n: Int) {\n let workload: Workload = Workload.nonBMPSlowestPrenormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n str._withNFCCodeUnits { cu in\n blackHole(cu)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringNormalization_emoji(_ n: Int) {\n let workload: Workload = Workload.emoji\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n str._withNFCCodeUnits { cu in\n blackHole(cu)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringNormalization_abnormal(_ n: Int) {\n let workload: Workload = Workload.abnormal\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n str._withNFCCodeUnits { cu in\n blackHole(cu)\n }\n }\n }\n}\n\n@inline(never)\npublic func run_StringNormalization_zalgo(_ n: Int) {\n let workload: Workload = Workload.zalgo\n let tripCount = workload.tripCount\n let payload = workload.payload\n for _ in 1...tripCount*n {\n for str in payload {\n str._withNFCCodeUnits { cu in\n blackHole(cu)\n }\n }\n }\n}\n\n\n\nstruct Workload {\n static let n = 100\n\n let name: String\n let payload: [String]\n var scaleMultiplier: Double\n\n init(name: String, payload: [String], scaleMultiplier: Double = 1.0) {\n self.name = name\n self.payload = payload\n self.scaleMultiplier = scaleMultiplier\n }\n\n var tripCount: Int {\n return Int(Double(Workload.n) * scaleMultiplier)\n }\n\n static let ascii = Workload(\n name: "ASCII",\n payload: """\n woodshed\n lakism\n gastroperiodynia\n afetal\n Casearia\n ramsch\n Nickieben\n undutifulness\n decorticate\n neognathic\n mentionable\n tetraphenol\n pseudonymal\n dislegitimate\n Discoidea\n criminative\n disintegratory\n executer\n Cylindrosporium\n complimentation\n Ixiama\n Araceae\n silaginoid\n derencephalus\n Lamiidae\n marrowlike\n ninepin\n trihemimer\n semibarbarous\n heresy\n existence\n fretless\n Amiranha\n handgravure\n orthotropic\n Susumu\n teleutospore\n sleazy\n shapeliness\n hepatotomy\n exclusivism\n stifler\n cunning\n isocyanuric\n pseudepigraphy\n carpetbagger\n unglory\n """.lines(),\n scaleMultiplier: 0.25\n )\n\n static let latin1 = Workload(\n name: "Latin1",\n payload: """\n café\n résumé\n caférésumé\n ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º\n 1+1=3\n ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹\n ¡¢£¤¥¦§¨©ª«¬®\n »¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍ\n ÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãä\n åæçèéêëìíîïðñò\n ÎÏÐÑÒÓÔÕÖëìíîïðñò\n óôõö÷øùúûüýþÿ\n 123.456£=>¥\n 123.456\n """.lines(),\n scaleMultiplier: 1/2\n )\n static let fastPrenormal = Workload(\n name: "FastPrenormal",\n payload: """\n ĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥ\n ĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸ\n ĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲ\n ųŴŵŶŷŸŹźŻżŽžſƀƁƂƃƄƅƆ\n ƇƈƉƊƋƌƍƎƏƐƑƒƓƔƕƖƗƘƙƚƛƜƝƞƟƠơƢƣƤƥƦƧƨƩƪƫƬƭƮƯưƱƲƳƴƵƶƷƸƹƺƻƼƽƾƿǀ\n Ƈ\n ǁǂǃDŽDždžLJLjljNJNjnjǍǎǏǐǑǒǓǔǕǖ\n ǗǘǙǚǛǜǝǞǟǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑ\n ȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬ\n ȒȓȔȕȖȗȘșȚțȜȝȞȟȠȡȢȣȤȥȦȧȨȩȪȫȬDzdzǴǵǶǷǸǹǺǻǼǽǾǿȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏȐȑ\n ȭȮȯȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏɐɑɒɓɔɕɖɗɘəɚɛɜɝɞɟɠɡɢɣɤɥɦɧɨɩɪɫɬɭɮɯɰ\n ɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃʄ\n ɱɲɳɴɵɶɷɸɹɺɻɼɽɾɿʀʁʂʃ\n ʅʆʇʈʉʊʋʌʍʎʏʐʑʒʓʔʕʖʗʘʙʚʛʜʝʞʟʠʡʢʣʤʥʦʧʨʩʪʫʬʭʮʯʰ\n ʱʲʳʴʵʶʷʸʹʺʻʼʽʾʿˀˁ˂˃˄˅ˆˇˈˉˊˋˌˍˎˏːˑ˒˓˔˕˖˗˘˙˚˛˜˝˞˟ˠˡˢˣˤ˥˦\n ˧˨˩˪˫ˬ˭ˮ˯˰˱˲˳˴˵˶˷˸˹˺˻˼˽˾\n """.lines(),\n scaleMultiplier: 1/10\n )\n static let slowerPrenormal = Workload(\n name: "SlowerPrenormal",\n payload: """\n Swiftに大幅な改良が施され、\n 安定していてしかも\n 直感的に使うことができる\n 向けプログラミング言語になりました。\n 이번 업데이트에서는 강력하면서도\n \u{201c}Hello\u{2010}world\u{2026}\u{201d}\n 平台的编程语言\n 功能强大且直观易用\n 而本次更新对其进行了全面优化\n в чащах юга жил-был цитрус\n \u{300c}\u{300e}今日は\u{3001}世界\u{3002}\u{300f}\u{300d}\n но фальшивый экземпляр\n """.lines(),\n scaleMultiplier: 1/10\n )\n // static let slowestPrenormal = """\n // """.lines()\n static let nonBMPSlowestPrenormal = Workload(\n name: "NonBMPSlowestPrenormal",\n payload: """\n 𓀀𓀤𓁓𓁲𓃔𓃗\n 𓀀𓀁𓀂𓀃𓀄𓀇𓀈𓀉𓀊𓀋𓀌𓀍𓀎𓀏𓀓𓀔𓀕𓀖𓀗𓀘𓀙𓀚𓀛𓀜𓀞𓀟𓀠𓀡𓀢𓀣\n 𓀤𓀥𓀦𓀧𓀨𓀩𓀪𓀫𓀬𓀭\n 𓁡𓁢𓁣𓁤𓁥𓁦𓁧𓁨𓁩𓁫𓁬𓁭𓁮𓁯𓁰𓁱𓁲𓁳𓁴𓁵𓁶𓁷𓁸\n 𓁹𓁺𓁓𓁔𓁕𓁻𓁼𓁽𓁾𓁿\n 𓀀𓀁𓀂𓀃𓀄𓃒𓃓𓃔𓃕𓃻𓃼𓃽𓃾𓃿𓄀𓄁𓄂𓄃𓄄𓄅𓄆𓄇𓄈𓄉𓄊𓄋𓄌𓄍𓄎\n 𓂿𓃀𓃁𓃂𓃃𓃄𓃅\n 𓃘𓃙𓃚𓃛𓃠𓃡𓃢𓃣𓃦𓃧𓃨𓃩𓃬𓃭𓃮𓃯𓃰𓃲𓃳𓃴𓃵𓃶𓃷𓃸\n 𓃘𓃙𓃚𓃛𓃠𓃡𓃢𓃣𓃦𓃧𓃨𓃩𓃬𓃭𓃮𓃯𓃰𓃲𓃳𓃴𓃵𓃶𓃷\n 𓀀𓀁𓀂𓀃𓀄𓆇𓆈𓆉𓆊𓆋𓆌𓆍𓆎𓆏𓆐𓆑𓆒𓆓𓆔𓆗𓆘𓆙𓆚𓆛𓆝𓆞𓆟𓆠𓆡𓆢𓆣𓆤\n 𓆥𓆦𓆧𓆨𓆩𓆪𓆫𓆬𓆭𓆮𓆯𓆰𓆱𓆲𓆳𓆴𓆵𓆶𓆷𓆸𓆹𓆺𓆻\n """.lines(),\n scaleMultiplier: 1/10\n )\n static let emoji = Workload(\n name: "Emoji",\n payload: """\n 👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿\n 👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏿👍🏻👍🏼👍🏽👍🏾\n 😀🧀😀😃😄😁🤣😂😅😆\n 😺🎃🤖👾😸😹😻😼😾😿🙀😽🙌🙏🤝👍✌🏽\n ☺️😊😇🙂😍😌😉🙃😘😗😙😚😛😝😜\n 😋🤑🤗🤓😎😒😏🤠🤡😞😔😟😕😖😣☹️🙁😫😩😤😠😑😐😶😡😯\n 😦😧😮😱😳😵😲😨😰😢😥\n 😪😓😭🤤😴🙄🤔🤥🤧🤢🤐😬😷🤒🤕😈💩👺👹👿👻💀☠️👽\n """.lines(),\n scaleMultiplier: 1/4\n )\n\n static let abnormal = Workload(\n name: "Abnormal",\n payload: """\n ae\u{301}ae\u{301}ae\u{302}ae\u{303}ae\u{304}ae\u{305}ae\u{306}ae\u{307}\n ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{301}ae\u{300}\n \u{f900}\u{f901}\u{f902}\u{f903}\u{f904}\u{f905}\u{f906}\u{f907}\u{f908}\u{f909}\u{f90a}\n \u{f90b}\u{f90c}\u{f90d}\u{f90e}\u{f90f}\u{f910}\u{f911}\u{f912}\u{f913}\u{f914}\u{f915}\u{f916}\u{f917}\u{f918}\u{f919}\n \u{f900}\u{f91a}\u{f91b}\u{f91c}\u{f91d}\u{f91e}\u{f91f}\u{f920}\u{f921}\u{f922}\n """.lines(),\n scaleMultiplier: 1/20\n )\n // static let pathological = """\n // """.lines()\n static let zalgo = Workload(\n name: "Zalgo",\n payload: """\n ṭ̴̵̶̷̸̢̧̨̡̛̤̥̦̩̪̫̬̭̮̯̰̖̗̘̙̜̝̞̟̠̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉ͣͤ̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚͜͟͢͝͞͠͡ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡\n h̀́̂̃\n è͇͈͉͍͎́̂̃̄̅̆̇̈̉͊͋͌͏̡̢̧̨̛͓͔͕͖͙͚̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭͇͈͉͍͎͐͑͒͗͛̊̋̌̍̎̏̐̑̒̓̔̀́͂̓̈́͆͊͋͌͘̕̚͜͟͝͞͠ͅ͏͓͔͕͖͐͑͒\n q̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆̕̚ͅ\n ư̴̵̶̷̸̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡\n ì̡̢̧̨̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̹̺̻̼͇͈͉͍͎́̂̃̄̉̊̋̌̍̎̏̐̑̒̓̽̾̿̀́͂̓̈́͆͊͋͌ͅ͏͓͔͕͖͙͐͑͒͗ͬͭͮ͘\n c̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼̀́̂̃̄̔̽̾̿̀́͂̓̈́͆ͣͤͥͦͧͨͩͪͫͬͭͮ̕̚͢͡ͅ\n k̴̵̶̷̸̡̢̧̨̛̖̗̘̙̜̝̞̟̠̣̤̥̦̩̪̫̬̭̮̯̰̱̲̳̹̺̻̼͇͈͉͍͎̀́̂̃̄̅̆̇̈̉̊̋̌̍̎̏̐̑̒̓̔̽̾̿̀́͂̓̈́͆͊͋͌̕̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡\n b̴̵̶̷̸̡̢̛̗̘̙̜̝̞̟̠̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡\n ŗ̴̵̶̷̸̨̛̩̪̫̯̰̱̲̳̹̺̻̼̬̭̮͇̗̘̙̜̝̞̟̤̥̦͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏̡̢͓͔͕͖͙͚̠̣͐͑͒͗͛ͣͤͥͦͧͨͩͪͫͬͭͮ͘͜͟͢͝͞͠͡\n o\n w̗̘͇͈͉͍͎̓̈́͆͊͋͌ͅ͏̛͓͔͕͖͙͚̙̜̹̺̻̼͐͑͒͗͛ͣͤͥͦ̽̾̿̀́͂ͧͨͩͪͫͬͭͮ͘̚͜͟͢͝͞͠͡\n n͇͈͉͍͎͊͋͌ͧͨͩͪͫͬͭͮ͏̛͓͔͕͖͙͚̗̘̙̜̹̺̻̼͐͑͒͗͛ͣͤͥͦ̽̾̿̀́͂̓̈́͆ͧͨͩͪͫͬͭͮ͘̚͜͟͢͝͞͠͡ͅ\n f̛̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͣͤͥͦ͘͜͟͢͝͞͠͡\n ơ̗̘̙̜̹̺̻̼͇͈͉͍͎̽̾̿̀́͂̓̈́͆͊͋͌̚ͅ͏͓͔͕͖͙͚͐͑͒͗͛ͥͦͧͨͩͪͫͬͭͮ͘\n xͣͤͥͦͧͨͩͪͫͬͭͮ\n """.lines(),\n scaleMultiplier: 1/100\n )\n\n static let longSharedPrefix = Workload(\n name: "LongSharedPrefix",\n payload: """\n http://www.dogbook.com/dog/239495828/friends/mutual/2939493815\n http://www.dogbook.com/dog/239495828/friends/mutual/3910583739\n http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared\n http://www.dogbook.com/dog/239495828/friends/mutual/3910583739/shared\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔\n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n 🤔Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.🤔\n """.lines()\n )\n\n}\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringComparison.swift | cpp_apple_swift_benchmark_single-source_StringComparison.swift | Swift | 26,520 | 0.95 | 0.077806 | 0.037037 | vue-tools | 896 | 2023-12-06T03:40:57.406226 | Apache-2.0 | false | d3477767678724ff4fff364beda6ceac |
//===--- StringEdits.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks: [BenchmarkInfo] = [\n BenchmarkInfo(\n name: "StringDistance.characters.mixed",\n runFunction: { n in\n run_characters(string: mixedString, ranges: mixedRanges, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(mixedRanges) }),\n BenchmarkInfo(\n name: "StringDistance.scalars.mixed",\n runFunction: { n in\n run_scalars(string: mixedString, ranges: mixedRanges, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(mixedRanges) }),\n BenchmarkInfo(\n name: "StringDistance.utf16.mixed",\n runFunction: { n in\n run_utf16(string: mixedString, ranges: mixedRanges, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(mixedRanges) }),\n BenchmarkInfo(\n name: "StringDistance.utf8.mixed",\n runFunction: { n in\n run_utf8(string: mixedString, ranges: mixedRanges, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(mixedRanges) }),\n BenchmarkInfo(\n name: "StringDistance.characters.ascii",\n runFunction: { n in\n run_characters(string: asciiString, ranges: asciiRanges, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(asciiRanges) }),\n BenchmarkInfo(\n name: "StringDistance.scalars.ascii",\n runFunction: { n in\n run_scalars(string: asciiString, ranges: asciiRanges, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(asciiRanges) }),\n BenchmarkInfo(\n name: "StringDistance.utf16.ascii",\n runFunction: { n in\n run_utf16(string: asciiString, ranges: asciiRanges, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(asciiRanges) }),\n BenchmarkInfo(\n name: "StringDistance.utf8.ascii",\n runFunction: { n in\n run_utf8(string: asciiString, ranges: asciiRanges, n: n)\n },\n tags: [.api, .String],\n setUpFunction: { blackHole(asciiRanges) }),\n]\n\n\nlet mixedString = #"""\n The powerful programming language that is also easy to learn.\n 손쉽게 학습할 수 있는 강력한 프로그래밍 언어.\n 🪙 A 🥞 short 🍰 piece 🫘 of 🌰 text 👨👨👧👧 with 👨👩👦 some 🚶🏽 emoji 🇺🇸🇨🇦 characters 🧈\n some🔩times 🛺 placed 🎣 in 🥌 the 🆘 mid🔀dle 🇦🇶or🏁 around 🏳️🌈 a 🍇 w🍑o🥒r🥨d\n Unicode is such fun!\n U̷n̷i̷c̷o̴d̴e̷ ̶i̸s̷ ̸s̵u̵c̸h̷ ̸f̵u̷n̴!̵\n U̴̡̲͋̾n̵̻̳͌ì̶̠̕c̴̭̈͘ǫ̷̯͋̊d̸͖̩̈̈́ḛ̴́ ̴̟͎͐̈i̴̦̓s̴̜̱͘ ̶̲̮̚s̶̙̞͘u̵͕̯̎̽c̵̛͕̜̓h̶̘̍̽ ̸̜̞̿f̵̤̽ṷ̴͇̎͘ń̷͓̒!̷͍̾̚\n U̷̢̢̧̨̼̬̰̪͓̞̠͔̗̼̙͕͕̭̻̗̮̮̥̣͉̫͉̬̲̺͍̺͊̂ͅ\#\n n̶̨̢̨̯͓̹̝̲̣̖̞̼̺̬̤̝̊̌́̑̋̋͜͝ͅ\#\n ḭ̸̦̺̺͉̳͎́͑\#\n c̵̛̘̥̮̙̥̟̘̝͙̤̮͉͔̭̺̺̅̀̽̒̽̏̊̆͒͌̂͌̌̓̈́̐̔̿̂͑͠͝͝ͅ\#\n ö̶̱̠̱̤̙͚͖̳̜̰̹̖̣̻͎͉̞̫̬̯͕̝͔̝̟̘͔̙̪̭̲́̆̂͑̌͂̉̀̓́̏̎̋͗͛͆̌̽͌̄̎̚͝͝͝͝ͅ\#\n d̶̨̨̡̡͙̟͉̱̗̝͙͍̮͍̘̮͔͑\#\n e̶̢͕̦̜͔̘̘̝͈̪̖̺̥̺̹͉͎͈̫̯̯̻͑͑̿̽͂̀̽͋́̎̈́̈̿͆̿̒̈́̽̔̇͐͛̀̓͆̏̾̀̌̈́̆̽̕ͅ\n """#\n\nlet mixedRanges = (\n generateRanges(for: mixedString, by: 1)\n + generateRanges(for: mixedString, by: 2)\n + generateRanges(for: mixedString, by: 4)\n + generateRanges(for: mixedString, by: 8)\n + generateRanges(for: mixedString, by: 16)\n + generateRanges(for: mixedString, by: 32)\n + generateRanges(for: mixedString, by: 64)\n + generateRanges(for: mixedString, by: 128)\n + generateRanges(for: mixedString, by: 256)\n + generateRanges(for: mixedString, by: 512))\n\nlet _asciiString = #"""\n Swift is a high-performance system programming language. It has a clean\n and modern syntax, offers seamless access to existing C and Objective-C code\n and frameworks, and is memory safe by default.\n\n Although inspired by Objective-C and many other languages, Swift is not itself\n a C-derived language. As a complete and independent language, Swift packages\n core features like flow control, data structures, and functions, with\n high-level constructs like objects, protocols, closures, and generics. Swift\n embraces modules, eliminating the need for headers and the code duplication\n they entail.\n\n Swift toolchains are created using the script\n [build-toolchain](https://github.com/apple/swift/blob/main/utils/build-toolchain).\n This script is used by swift.org's CI to produce snapshots and can allow for\n one to locally reproduce such builds for development or distribution purposes.\n A typical invocation looks like the following:\n\n ```\n $ ./swift/utils/build-toolchain $BUNDLE_PREFIX\n ```\n\n where ``$BUNDLE_PREFIX`` is a string that will be prepended to the build date\n to give the bundle identifier of the toolchain's ``Info.plist``. For instance,\n if ``$BUNDLE_PREFIX`` was ``com.example``, the toolchain produced will have\n the bundle identifier ``com.example.YYYYMMDD``. It will be created in the\n directory you run the script with a filename of the form:\n ``swift-LOCAL-YYYY-MM-DD-a-osx.tar.gz``.\n """#\nlet asciiString = String(repeating: _asciiString, count: 10)\n\nlet asciiRanges = (\n generateRanges(for: asciiString, by: 1)\n + generateRanges(for: asciiString, by: 2)\n + generateRanges(for: asciiString, by: 4)\n + generateRanges(for: asciiString, by: 8)\n + generateRanges(for: asciiString, by: 16)\n + generateRanges(for: asciiString, by: 32)\n + generateRanges(for: asciiString, by: 64)\n + generateRanges(for: asciiString, by: 128)\n + generateRanges(for: asciiString, by: 256)\n + generateRanges(for: asciiString, by: 512))\n\nfunc generateRanges(for string: String, by step: Int) -> [Range<String.Index>] {\n var remaining = step\n var i = string.startIndex\n var last = i\n\n var ranges: [Range<String.Index>] = []\n while i < string.endIndex {\n string.unicodeScalars.formIndex(after: &i)\n remaining -= 1\n if remaining == 0 {\n ranges.append(last ..< i)\n remaining = step\n last = i\n }\n }\n ranges.append(last ..< i)\n return ranges\n}\n\nfunc run_characters(string: String, ranges: [Range<String.Index>], n: Int) {\n var c = 0\n for _ in 0 ..< n {\n for r in ranges {\n c += string.distance(from: r.lowerBound, to: r.upperBound)\n }\n }\n blackHole(c)\n}\n\nfunc run_scalars(string: String, ranges: [Range<String.Index>], n: Int) {\n var c = 0\n for _ in 0 ..< n {\n for r in ranges {\n c += string.unicodeScalars.distance(from: r.lowerBound, to: r.upperBound)\n }\n }\n blackHole(c)\n}\n\nfunc run_utf16(string: String, ranges: [Range<String.Index>], n: Int) {\n var c = 0\n for _ in 0 ..< n {\n for r in ranges {\n c += string.utf16.distance(from: r.lowerBound, to: r.upperBound)\n }\n }\n blackHole(c)\n}\n\nfunc run_utf8(string: String, ranges: [Range<String.Index>], n: Int) {\n var c = 0\n for _ in 0 ..< n {\n for r in ranges {\n c += string.utf8.distance(from: r.lowerBound, to: r.upperBound)\n }\n }\n blackHole(c)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringDistance.swift | cpp_apple_swift_benchmark_single-source_StringDistance.swift | Swift | 7,519 | 0.95 | 0.181373 | 0.058824 | node-utils | 476 | 2024-03-01T17:50:25.208331 | BSD-3-Clause | false | 8ed53ed77b75ce6a30b13cfcc2f5dddf |
//===--- StringEdits.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n#if canImport(Glibc)\nimport Glibc\n#elseif canImport(Musl)\nimport Musl\n#elseif os(Windows)\nimport MSVCRT\n#else\nimport Darwin\n#endif\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "StringEdits",\n runFunction: run_StringEdits,\n tags: [.validation, .api, .String],\n legacyFactor: 100),\n]\n\nlet editWords: [String] = [\n "woodshed",\n "lakism",\n "gastroperiodynia",\n]\n\nlet alphabet = "abcdefghijklmnopqrstuvwxyz"\n/// All edits that are one edit away from `word`\nfunc edits(_ word: String) -> Set<String> {\n let splits = word.indices.map {\n (String(word[..<$0]), String(word[$0...]))\n }\n\n var result: Array<String> = []\n\n for (left, right) in splits {\n // drop a character\n result.append(left + right.dropFirst())\n\n // transpose two characters\n if let fst = right.first {\n let drop1 = right.dropFirst()\n if let snd = drop1.first {\n result.append(left + [snd,fst] + drop1.dropFirst())\n }\n }\n\n // replace each character with another\n for letter in alphabet {\n result.append(left + [letter] + right.dropFirst())\n }\n\n // insert rogue characters\n for letter in alphabet {\n result.append(left + [letter] + right)\n }\n }\n\n // have to map back to strings right at the end\n return Set(result)\n}\n\n@inline(never)\npublic func run_StringEdits(_ n: Int) {\n for _ in 1...n {\n for word in editWords {\n _ = edits(word)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringEdits.swift | cpp_apple_swift_benchmark_single-source_StringEdits.swift | Swift | 1,945 | 0.95 | 0.123457 | 0.314286 | node-utils | 768 | 2023-12-16T10:29:56.041646 | GPL-3.0 | false | a1d46fe8d9625ba96e3a1f409db2f927 |
//===--- StringEnum.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "StringEnumRawValueInitialization",\n runFunction: run_StringEnumRawValueInitialization,\n tags: [.validation, .api, .String],\n legacyFactor: 20),\n]\n\nenum TestEnum : String {\n case c1 = "Swift"\n case c2 = "is"\n case c3 = "a"\n case c4 = "general-purpose"\n case c5 = "programming language"\n case c7 = "built"\n case c8 = "using"\n case c10 = "modern"\n case c11 = "approach"\n case c12 = "to"\n case c13 = "safety,"\n case c14 = "performance,"\n case c15 = "and"\n case c16 = "software"\n case c17 = "design"\n case c18 = "patterns."\n case c19 = ""\n case c20 = "The"\n case c21 = "goal"\n case c22 = "of"\n case c23 = "the"\n case c25 = "project"\n case c28 = "create"\n case c30 = "best"\n case c31 = "available"\n case c33 = "for"\n case c34 = "uses"\n case c35 = "ranging"\n case c36 = "from"\n case c37 = "systems"\n case c40 = "mobile"\n case c42 = "desktop"\n case c43 = "apps,"\n case c44 = "scaling"\n case c45 = "up"\n case c47 = "cloud"\n case c48 = "services."\n case c49 = "Most"\n case c50 = "importantly,"\n case c53 = "designed"\n case c55 = "make"\n case c56 = "writing"\n case c58 = "maintaining"\n case c59 = "correct"\n case c60 = "programs"\n case c61 = "easier"\n case c64 = "developer."\n case c65 = "To"\n case c66 = "achieve"\n case c67 = "this"\n case c68 = "goal,"\n case c69 = "we"\n case c70 = "believe"\n case c71 = "that"\n case c73 = "most"\n case c74 = "obvious"\n case c75 = "way"\n case c77 = "write"\n case c79 = "code"\n case c80 = "must"\n case c81 = "also"\n case c82 = "be:"\n case c84 = "Safe."\n case c92 = "should"\n case c94 = "behave"\n case c95 = "in"\n case c97 = "safe"\n case c98 = "manner."\n case c99 = "Undefined"\n case c100 = "behavior"\n case c103 = "enemy"\n case c107 = "developer"\n case c108 = "mistakes"\n case c110 = "be"\n case c111 = "caught"\n case c112 = "before"\n case c116 = "production."\n case c117 = "Opting"\n case c119 = "safety"\n case c120 = "sometimes"\n case c121 = "means"\n case c123 = "will"\n case c124 = "feel"\n case c125 = "strict,"\n case c126 = "but"\n case c130 = "clarity"\n case c131 = "saves"\n case c132 = "time"\n case c135 = "long"\n case c136 = "run."\n case c138 = "Fast."\n case c141 = "intended"\n case c142 = "as"\n case c144 = "replacement"\n case c146 = "C-based"\n case c147 = "languages"\n case c148 = "(C, C++, Objective-C)."\n case c152 = "As"\n case c153 = "such,"\n case c157 = "comparable"\n case c159 = "those"\n case c162 = "performance"\n case c165 = "tasks."\n case c166 = "Performance"\n case c170 = "predictable"\n case c172 = "consistent,"\n case c173 = "not"\n case c174 = "just"\n case c175 = "fast"\n case c177 = "short"\n case c178 = "bursts"\n case c180 = "require"\n case c181 = "clean-up"\n case c182 = "later."\n case c183 = "There"\n case c184 = "are"\n case c185 = "lots"\n case c188 = "with"\n case c189 = "novel"\n case c190 = "features"\n case c191 = "—"\n case c192 = "being"\n case c195 = "rare."\n case c197 = "Expressive."\n case c199 = "benefits"\n case c201 = "decades"\n case c203 = "advancement"\n case c205 = "computer"\n case c206 = "science"\n case c208 = "offer"\n case c209 = "syntax"\n case c213 = "joy"\n case c215 = "use,"\n case c219 = "developers"\n case c220 = "expect."\n case c221 = "But"\n case c224 = "never"\n case c225 = "done."\n case c226 = "We"\n case c228 = "monitor"\n case c230 = "advancements"\n case c232 = "embrace"\n case c233 = "what"\n case c234 = "works,"\n case c235 = "continually"\n case c236 = "evolving"\n case c240 = "even"\n case c241 = "better."\n case c243 = "Tools"\n case c246 = "critical"\n case c247 = "part"\n case c251 = "ecosystem."\n case c253 = "strive"\n case c255 = "integrate"\n case c256 = "well"\n case c257 = "within"\n case c259 = "developer’s"\n case c260 = "toolset,"\n case c262 = "build"\n case c263 = "quickly,"\n case c265 = "present"\n case c266 = "excellent"\n case c267 = "diagnostics,"\n case c270 = "enable"\n case c271 = "interactive"\n case c272 = "development"\n case c273 = "experiences."\n case c275 = "can"\n case c278 = "so"\n case c279 = "much"\n case c280 = "more"\n case c281 = "powerful,"\n case c282 = "like"\n case c283 = "Swift-based"\n case c284 = "playgrounds"\n case c285 = "do"\n case c287 = "Xcode,"\n case c288 = "or"\n case c290 = "web-based"\n case c291 = "REPL"\n case c293 = "when"\n case c294 = "working"\n case c296 = "Linux"\n case c297 = "server-side"\n case c298 = "code."\n}\n\n@inline(never)\nfunc convert(_ s: String) {\n blackHole(TestEnum(rawValue: s))\n}\n\n@inline(never)\npublic func run_StringEnumRawValueInitialization(_ n: Int) {\n let first = "Swift"\n let short = "To"\n let long = "(C, C++, Objective-C)."\n let last = "code."\n for _ in 1...100*n {\n convert(first)\n convert(short)\n convert(long)\n convert(last)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringEnum.swift | cpp_apple_swift_benchmark_single-source_StringEnum.swift | Swift | 5,374 | 0.95 | 0.017544 | 0.049327 | python-kit | 693 | 2023-11-07T16:49:50.926984 | MIT | false | a6a3e62a18a52405e5a407c41f6721cf |
//===--- StringInterpolation.swift ----------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "StringInterpolation",\n runFunction: run_StringInterpolation,\n tags: [.validation, .api, .String],\n legacyFactor: 100),\n BenchmarkInfo(\n name: "StringInterpolationSmall",\n runFunction: run_StringInterpolationSmall,\n tags: [.validation, .api, .String],\n legacyFactor: 10),\n BenchmarkInfo(\n name: "StringInterpolationManySmallSegments",\n runFunction: run_StringInterpolationManySmallSegments,\n tags: [.validation, .api, .String],\n legacyFactor: 100),\n]\n\nclass RefTypePrintable : CustomStringConvertible {\n var description: String {\n return "01234567890123456789012345678901234567890123456789"\n }\n}\n\n@inline(never)\npublic func run_StringInterpolation(_ n: Int) {\n let reps = 100\n let refResult = reps\n let anInt: Int64 = 0x1234567812345678\n let aRefCountedObject = RefTypePrintable()\n\n for _ in 1...n {\n var result = 0\n for _ in 1...reps {\n let s: String = getString(\n "\(anInt) abcdefdhijklmn \(aRefCountedObject) abcdefdhijklmn \u{01}")\n let utf16 = s.utf16\n\n // FIXME: if String is not stored as UTF-16 on this platform, then the\n // following operation has a non-trivial cost and needs to be replaced\n // with an operation on the native storage type.\n result = result &+ Int(utf16.last!)\n blackHole(s)\n }\n check(result == refResult)\n }\n}\n\n@inline(never)\npublic func run_StringInterpolationSmall(_ n: Int) {\n let reps = 100\n let refResult = reps\n let anInt: Int64 = 0x42\n\n for _ in 1...10*n {\n var result = 0\n for _ in 1...reps {\n let s: String = getString(\n "\(getString("int")): \(anInt) \(getString("abc")) \u{01}")\n result = result &+ Int(s.utf8.last!)\n blackHole(s)\n }\n check(result == refResult)\n }\n}\n\n@inline(never)\npublic func run_StringInterpolationManySmallSegments(_ n: Int) {\n let numHex = min(UInt64(n), 0x0FFF_FFFF_FFFF_FFFF)\n let numOct = min(UInt64(n), 0x0000_03FF_FFFF_FFFF)\n let numBin = min(UInt64(n), 0x7FFF)\n let segments = [\n "abc",\n String(numHex, radix: 16),\n "0123456789",\n String(Double.pi/2),\n "*barely* small!",\n String(numOct, radix: 8),\n "",\n String(numBin, radix: 2),\n ]\n assert(segments.count == 8)\n\n func getSegment(_ i: Int) -> String {\n return getString(segments[i])\n }\n\n let reps = 100\n for _ in 1...n {\n for _ in 1...reps {\n blackHole("""\n \(getSegment(0)) \(getSegment(1))/\(getSegment(2))_\(getSegment(3))\n \(getSegment(4)) \(getSegment(5)), \(getSegment(6))~~\(getSegment(7))\n """)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringInterpolation.swift | cpp_apple_swift_benchmark_single-source_StringInterpolation.swift | Swift | 3,131 | 0.95 | 0.09009 | 0.14 | react-lib | 546 | 2025-03-18T14:06:03.844558 | MIT | false | 83c6c2825b6cfe99d891d745597b433c |
//===--- StringMatch.swift ------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n#if canImport(Glibc)\nimport Glibc\n#elseif canImport(Musl)\nimport Musl\n#elseif os(Windows)\nimport MSVCRT\n#else\nimport Darwin\n#endif\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "StringMatch",\n runFunction: run_StringMatch,\n tags: [.validation, .api, .String],\n legacyFactor: 100)\n\n/* match: search for regexp anywhere in text */\nfunc match(regexp: String, text: String) -> Bool {\n if regexp.first == "^" {\n return matchHere(regexp.dropFirst(), text[...])\n }\n\n var idx = text.startIndex\n while true { // must look even if string is empty\n if matchHere(regexp[...], text[idx..<text.endIndex]) {\n return true\n }\n guard idx != text.endIndex else { break }\n // do while sufficed in the original C version...\n text.formIndex(after: &idx)\n } // while idx++ != string.endIndex\n\n return false\n}\n\n/* matchhere: search for regexp at beginning of text */\nfunc matchHere(_ regexp: Substring, _ text: Substring) -> Bool {\n if regexp.isEmpty {\n return true\n }\n\n if let c = regexp.first, regexp.dropFirst().first == "*" {\n return matchStar(c, regexp.dropFirst(2), text)\n }\n\n if regexp.first == "$" && regexp.dropFirst().isEmpty {\n return text.isEmpty\n }\n\n if let tc = text.first, let rc = regexp.first, rc == "." || tc == rc {\n return matchHere(regexp.dropFirst(), text.dropFirst())\n }\n\n return false\n}\n\n/* matchstar: search for c*regexp at beginning of text */\nfunc matchStar(_ c: Character, _ regexp: Substring, _ text: Substring) -> Bool {\n var idx = text.startIndex\n while true { /* a * matches zero or more instances */\n if matchHere(regexp, text[idx..<text.endIndex]) {\n return true\n }\n if idx == text.endIndex || (text[idx] != c && c != ".") {\n return false\n }\n text.formIndex(after: &idx)\n }\n}\n\nlet tests: KeyValuePairs = [\n "^h..lo*!$":"hellooooo!",\n "^h..lo*!$":"hella noms",\n ".ab":"abracadabra!",\n "s.*":"saaaad!",\n "...e.$":"\"Ganymede,\" he continued, \"is the largest moon in the Solar System\"",\n "🤠*":"even 🤠🤠🤠 are supported",\n]\n\n@inline(never)\npublic func run_StringMatch(_ n: Int) {\n for _ in 1...n {\n for (regex, text) in tests {\n _ = match(regexp: regex,text: text)\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringMatch.swift | cpp_apple_swift_benchmark_single-source_StringMatch.swift | Swift | 2,744 | 0.95 | 0.207921 | 0.227273 | vue-tools | 438 | 2024-11-15T05:22:47.234981 | Apache-2.0 | false | 7ce76e5566232dbd8a3f2169d4173d42 |
// StringRemoveDupes benchmark\n//\n// Source: https://gist.github.com/airspeedswift/83eee31e1d9e52fd5570\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "StringRemoveDupes",\n runFunction: run_StringRemoveDupes,\n tags: [.validation, .String]\n )\n\n@inline(never)\npublic func run_StringRemoveDupes(_ n: Int) {\n let textLengthRef = 25\n let text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +\n "Morbi nisi metus, accumsan eu sagittis et, condimentum ut " +\n "arcu. Morbi aliquet porta velit, accumsan aliquam ante " +\n "facilisis non. Maecenas lobortis erat vel elit fringilla " +\n "blandit. Praesent euismod mauris sodales velit facilisis " +\n "blandit. Morbi leo neque, finibus ut mi in, auctor sagittis."\n var s = ""\n\n for _ in 1...10*n {\n s = text.removeDuplicates()\n\n if s.count != textLengthRef {\n break\n }\n }\n\n check(s.count == textLengthRef)\n}\n\n// removes all but first occurrence from a sequence, returning an array.\n// requires elements to be hashable, not just equatable, but the alternative\n// of using contains is very inefficient\n// alternatively, could require comparable, sort, and remove adjacent dupes\nfunc uniq<S: Sequence,\n E: Hashable>(_ seq: S) -> [E] where E == S.Element {\n var seen: [S.Element:Int] = [:]\n return seq.filter { seen.updateValue(1, forKey: $0) == nil }\n}\n\n// removeDuplicates returns a version of the String with\n// all duplicates removed\nextension String {\n func removeDuplicates() -> String {\n return String(uniq(self))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringRemoveDupes.swift | cpp_apple_swift_benchmark_single-source_StringRemoveDupes.swift | Swift | 1,602 | 0.95 | 0.038462 | 0.204545 | node-utils | 353 | 2024-10-06T02:05:36.109256 | GPL-3.0 | false | 46689a3d7fa5c63bd097705d946fa9ef |
//===--- StringRepeating.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(name: "String.initRepeating.1AsciiChar.Count100",\n runFunction: run_singleAsciiCharacterCount100,\n tags: [.validation, .api, .String]),\n BenchmarkInfo(name: "String.initRepeating.26AsciiChar.Count2",\n runFunction: run_26AsciiCharactersCount2,\n tags: [.validation, .api, .String]),\n BenchmarkInfo(name: "String.initRepeating.33CyrillicChar.Count2",\n runFunction: run_33CyrillicCharactersCount2,\n tags: [.validation, .api, .String]),\n BenchmarkInfo(name: "String.initRepeating.longMixStr.Count100",\n runFunction: run_longMixedStringCount100,\n tags: [.validation, .api, .String])\n]\n\n@inline(never)\npublic func run_singleAsciiCharacterCount100(N: Int) {\n let string = "x"\n for _ in 1...200*N {\n blackHole(String(repeating: getString(string), count: 100))\n }\n}\n\n@inline(never)\npublic func run_26AsciiCharactersCount2(N: Int) {\n let string = "abcdefghijklmnopqrstuvwxyz"\n for _ in 1...200*N {\n blackHole(String(repeating: getString(string), count: 2))\n }\n}\n\n@inline(never)\npublic func run_33CyrillicCharactersCount2(N: Int) {\n let string = "абвгґдеєжзиіїйклмнопрстуфхцчшщьюя"\n for _ in 1...200*N {\n blackHole(String(repeating: getString(string), count: 2))\n }\n}\n\n@inline(never)\npublic func run_longMixedStringCount100(N: Int) {\n let string = """\n Swift is a multi-paradigm, compiled programming language created for\n iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is\n designed to work with Apple's Cocoa and Cocoa Touch frameworks and the\n large body of existing Objective-C code written for Apple products. Swift\n is intended to be more resilient to erroneous code (\"safer\") than\n Objective-C and also more concise. It is built with the LLVM compiler\n framework included in Xcode 6 and later and uses the Objective-C runtime,\n which allows C, Objective-C, C++ and Swift code to run within a single\n program.\n Існує багато варіацій уривків з Lorem Ipsum, але більшість з них зазнала\n певних змін на кшталт жартівливих вставок або змішування слів, які навіть\n не виглядають правдоподібно.\n 日本語の場合はランダムに生成された文章以外に、\n 著作権が切れた小説などが利用されることもある。\n 🦩\n """\n for _ in 1...200*N {\n blackHole(String(repeating: getString(string), count: 100))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringRepeating.swift | cpp_apple_swift_benchmark_single-source_StringRepeating.swift | Swift | 3,191 | 0.95 | 0.105263 | 0.157143 | node-utils | 912 | 2024-01-18T06:03:46.059761 | BSD-3-Clause | false | 86cda387961a28518e74b5bd02025289 |
//===--- StringReplaceSubrange.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\nlet tags: [BenchmarkCategory] = [.validation, .api, .String, .cpubench]\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "String.replaceSubrange.String.Small",\n runFunction: { replaceSubrange($0, smallString, with: "t") },\n tags: tags\n ),\n BenchmarkInfo(\n name: "String.replaceSubrange.String",\n runFunction: { replaceSubrange($0, largeString, with: "t") },\n tags: tags\n ),\n BenchmarkInfo(\n name: "String.replaceSubrange.Substring.Small",\n runFunction: { replaceSubrange($0, smallString, with: "t"[...]) },\n tags: tags\n ),\n BenchmarkInfo(\n name: "String.replaceSubrange.Substring",\n runFunction: { replaceSubrange($0, largeString, with: "t"[...]) },\n tags: tags\n ),\n BenchmarkInfo(\n name: "String.replaceSubrange.ArrChar.Small",\n runFunction: { replaceSubrange($0, smallString, with: arrayCharacter) },\n tags: tags\n ),\n BenchmarkInfo(\n name: "String.replaceSubrange.ArrChar",\n runFunction: { replaceSubrange($0, largeString, with: arrayCharacter) },\n tags: tags\n ),\n BenchmarkInfo(\n name: "String.replaceSubrange.RepChar.Small",\n runFunction: { replaceSubrange($0, smallString, with: repeatedCharacter) },\n tags: tags\n ),\n BenchmarkInfo(\n name: "String.replaceSubrange.RepChar",\n runFunction: { replaceSubrange($0, largeString, with: repeatedCharacter) },\n tags: tags\n ),\n]\n\nlet smallString = "coffee"\nlet largeString = "coffee\u{301}coffeecoffeecoffeecoffee"\n\nlet arrayCharacter = Array<Character>(["t"])\nlet repeatedCharacter = repeatElement(Character("t"), count: 1)\n\n@inline(never)\nprivate func replaceSubrange<C: Collection>(\n _ n: Int, _ string: String, with newElements: C\n) where C.Element == Character {\n var copy = getString(string)\n let range = string.startIndex..<string.index(after: string.startIndex)\n for _ in 0 ..< 500 * n {\n copy.replaceSubrange(range, with: newElements)\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringReplaceSubrange.swift | cpp_apple_swift_benchmark_single-source_StringReplaceSubrange.swift | Swift | 2,445 | 0.95 | 0.04 | 0.15942 | node-utils | 449 | 2023-11-11T06:48:00.375929 | Apache-2.0 | false | 3591a3faed0ab7a9b0e7b9881b081426 |
//===--- StringSplitting.swift --------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "LineSink.bytes.alpha",\n runFunction: run_LinkSink_bytes_alpha,\n tags: [.validation, .String],\n setUpFunction: setup),\n BenchmarkInfo(\n name: "LineSink.bytes.complex",\n runFunction: run_LinkSink_bytes_complex,\n tags: [.validation, .String],\n setUpFunction: setup),\n BenchmarkInfo(\n name: "LineSink.scalars.alpha",\n runFunction: run_LinkSink_scalars_alpha,\n tags: [.validation, .String],\n setUpFunction: setup),\n BenchmarkInfo(\n name: "LineSink.scalars.complex",\n runFunction: run_LinkSink_scalars_complex,\n tags: [.validation, .String],\n setUpFunction: setup),\n BenchmarkInfo(\n name: "LineSink.characters.alpha",\n runFunction: run_LinkSink_characters_alpha,\n tags: [.validation, .String],\n setUpFunction: setup),\n BenchmarkInfo(\n name: "LineSink.characters.complex",\n runFunction: run_LinkSink_characters_complex,\n tags: [.validation, .String],\n setUpFunction: setup),\n]\n\n\n// Line-sink benchmarks: Implement `lines`-like functionality\nenum View {\n case character\n case scalar\n case utf8\n}\n\n@inline(__always) // Constant fold the switch away, inline closures\nfileprivate func lineSink(_ workload: String, view: View, sink: (String) -> ()) {\n switch view {\n case .character:\n var iter = workload.makeIterator()\n _linesByCharacters(source: { iter.next() }, sink: sink)\n case .scalar:\n var iter = workload.unicodeScalars.makeIterator()\n _linesByScalars(source: { iter.next() }, sink: sink)\n case .utf8:\n var iter = workload.utf8.makeIterator()\n _linesByBytes(source: { iter.next() }, sink: sink)\n }\n}\n\n\n// Inline always to try to ignore any closure stuff\n@inline(__always)\nfileprivate func _linesByCharacters(\n source characterSource: () throws -> Character?,\n sink lineSink: (String) -> ()\n) rethrows {\n var buffer = ""\n func yield() {\n lineSink(buffer)\n buffer.removeAll(keepingCapacity: true)\n }\n while let c = try characterSource() {\n if c.isNewline {\n yield()\n } else {\n buffer.append(c)\n }\n }\n\n // Don't emit an empty newline when there is no more content (e.g. end of file)\n if !buffer.isEmpty {\n yield()\n }\n}\n\n// Inline always to try to ignore any closure stuff\n@inline(__always)\nfileprivate func _linesByScalars(\n source scalarSource: () throws -> Unicode.Scalar?,\n sink lineSink: (String) -> ()\n) rethrows {\n guard #available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) else {\n fatalError("unavailable")\n }\n\n var buffer: Array<UInt8> = []\n func yield() {\n lineSink(String(decoding: buffer, as: UTF8.self))\n buffer.removeAll(keepingCapacity: true)\n }\n\n let _CR = Unicode.Scalar(0x0D)!\n let _LF = Unicode.Scalar(0x0A)!\n\n while let first = try scalarSource() {\n switch first.value {\n case _CR.value:\n yield()\n guard let second = try scalarSource() else { return }\n if second != _LF { buffer.append(contentsOf: second.utf8) }\n case 0x000A..<0x000D /* LF ..< CR */: yield()\n case 0x0085 /* NEXT LINE (NEL) */: yield()\n case 0x2028 /* LINE SEPARATOR */: yield()\n case 0x2029 /* PARAGRAPH SEPARATOR */: yield()\n default: buffer.append(contentsOf: first.utf8)\n }\n }\n\n // Don't emit an empty newline when there is no more content (e.g. end of file)\n if !buffer.isEmpty {\n yield()\n }\n}\n\n\n@inline(__always)\nfileprivate func _linesByBytes(\n source byteSource: () throws -> UInt8?,\n sink lineSink: (String) -> ()\n) rethrows {\n\n let _CR: UInt8 = 0x0D\n let _LF: UInt8 = 0x0A\n\n var buffer: Array<UInt8> = []\n func yield() {\n lineSink(String(decoding: buffer, as: UTF8.self))\n buffer.removeAll(keepingCapacity: true)\n }\n\n /*\n 0D 0A: CR-LF\n 0A | 0B | 0C | 0D: LF, VT, FF, CR\n E2 80 A8: U+2028 (LINE SEPARATOR)\n E2 80 A9: U+2029 (PARAGRAPH SEPARATOR)\n */\n while let first = try byteSource() {\n switch first {\n case _CR:\n yield()\n // Swallow up any subsequent LF\n guard let next = try byteSource() else { return }\n if next != _LF { buffer.append(next) }\n case 0x0A..<0x0D: yield()\n\n case 0xE2:\n // Try to read: 80 [A8 | A9].\n // If we can't, then we put the byte in the buffer for error correction\n guard let next = try byteSource() else {\n buffer.append(first)\n yield()\n return\n }\n guard next == 0x80 else {\n buffer.append(first)\n buffer.append(next)\n continue\n }\n guard let fin = try byteSource() else {\n buffer.append(first)\n buffer.append(next)\n yield()\n return\n }\n guard fin == 0xA8 || fin == 0xA9 else {\n buffer.append(first)\n buffer.append(next)\n buffer.append(fin)\n continue\n }\n yield()\n default:\n buffer.append(first)\n }\n }\n // Don't emit an empty newline when there is no more content (e.g. end of file)\n if !buffer.isEmpty {\n yield()\n }\n}\n\n// 1-byte sequences\nprivate let ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."\n\n// 2-byte sequences\nprivate let russian = "Ру́сский язы́к один из восточнославянских языков, национальный язык русского народа."\n// 3-byte sequences\nprivate let japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。"\n// 4-byte sequences\n// Most commonly emoji, which are usually mixed with other text.\nprivate let emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭."\n\nprivate let longComplexNewlines: String = {\n var longStr = ascii + russian + japanese + emoji + "\n"\n var str = longStr\n str += longStr.split(separator: " ").joined(separator: "\n")\n str += longStr.split(separator: " ").joined(separator: "\r\n")\n str += longStr.split(separator: " ").joined(separator: "\r")\n str += longStr.split(separator: " ").joined(separator: "\u{0B}")\n str += longStr.split(separator: " ").joined(separator: "\u{0C}")\n str += longStr.split(separator: " ").joined(separator: "\u{2028}")\n str += longStr.split(separator: " ").joined(separator: "\u{2029}")\n str += "\n\n"\n return str\n}()\n\npublic func run_LinkSink_bytes_alpha(_ n: Int) {\n let str = alphaInteriorNewlines\n for _ in 0..<(n*50) {\n lineSink(str, view: .utf8, sink: blackHole)\n }\n}\npublic func run_LinkSink_bytes_complex(_ n: Int) {\n let str = longComplexNewlines\n for _ in 0..<n {\n lineSink(str, view: .utf8, sink: blackHole)\n }\n}\npublic func run_LinkSink_scalars_alpha(_ n: Int) {\n let str = alphaInteriorNewlines\n for _ in 0..<(n*50) {\n lineSink(str, view: .scalar, sink: blackHole)\n }\n}\npublic func run_LinkSink_scalars_complex(_ n: Int) {\n let str = longComplexNewlines\n for _ in 0..<n {\n lineSink(str, view: .utf8, sink: blackHole)\n }\n}\npublic func run_LinkSink_characters_alpha(_ n: Int) {\n let str = alphaInteriorNewlines\n for _ in 0..<(n*50) {\n lineSink(str, view: .character, sink: blackHole)\n }\n}\npublic func run_LinkSink_characters_complex(_ n: Int) {\n let str = longComplexNewlines\n for _ in 0..<n {\n lineSink(str, view: .character, sink: blackHole)\n }\n}\n\nfileprivate func setup() {\n var utf8Alpha: Array<String> = []\n lineSink(alphaInteriorNewlines, view: .utf8) { utf8Alpha.append($0) }\n\n var scalarAlpha: Array<String> = []\n lineSink(alphaInteriorNewlines, view: .scalar) { scalarAlpha.append($0) }\n\n var characterAlpha: Array<String> = []\n lineSink(alphaInteriorNewlines, view: .character) { characterAlpha.append($0) }\n\n check(utf8Alpha == scalarAlpha)\n check(utf8Alpha == characterAlpha)\n\n var utf8Complex: Array<String> = []\n lineSink(longComplexNewlines, view: .utf8) { utf8Complex.append($0) }\n\n var scalarComplex: Array<String> = []\n lineSink(longComplexNewlines, view: .scalar) { scalarComplex.append($0) }\n\n var characterComplex: Array<String> = []\n lineSink(longComplexNewlines, view: .character) { characterComplex.append($0) }\n\n check(utf8Complex == scalarComplex)\n check(utf8Complex == characterComplex)\n\n print("preconditions checked")\n}\n\n\nprivate let alphaInteriorNewlines: String =\n """\n abc\(Unicode.Scalar(0x0A)! // LF\n )def\(Unicode.Scalar(0x0B)! // VT\n )ghi\(Unicode.Scalar(0x0C)! // FF\n )jkl\(Unicode.Scalar(0x0D)! // CR\n )mno\(Unicode.Scalar(0x0D)!)\(Unicode.Scalar(0x0A)! // CR-LF\n )pqr\(Unicode.Scalar(0x2028)! // LS\n )stu\(Unicode.Scalar(0x2029)! // PS\n )vwx\n yz\n """\n\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringSplitting.swift | cpp_apple_swift_benchmark_single-source_StringSplitting.swift | Swift | 9,487 | 0.95 | 0.110749 | 0.099631 | python-kit | 900 | 2024-11-19T00:36:24.460788 | MIT | false | 0876f75675b4dbac5dc43f3cefdb0049 |
//===--- StringSwitch.swift -------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2020 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "StringSwitch",\n runFunction: run_StringSwitch,\n tags: [.validation, .api])\n]\n\n@inline(never)\nfunc getIndex(_ s: String) -> Int {\n switch s {\n case "Swift": return 0\n case "is": return 1\n case "a": return 2\n case "general-purpose": return 3\n case "programming language": return 4\n case "built": return 5\n case "using": return 6\n case "modern": return 7\n case "approach": return 8\n case "to": return 9\n case "safety,": return 10\n case "performance,": return 11\n case "and": return 12\n case "software": return 13\n case "design": return 14\n case "patterns.": return 15\n case "": return 16\n case "The": return 17\n case "goal": return 18\n case "of": return 19\n case "the": return 20\n case "project": return 21\n case "create": return 22\n case "best": return 23\n case "available": return 24\n case "for": return 25\n case "uses": return 26\n case "ranging": return 27\n case "from": return 28\n case "systems": return 29\n case "mobile": return 30\n case "desktop": return 31\n case "apps,": return 32\n case "scaling": return 33\n case "up": return 34\n case "cloud": return 35\n case "services.": return 36\n case "Most": return 37\n case "importantly,": return 38\n case "designed": return 39\n case "make": return 40\n case "writing": return 41\n case "maintaining": return 42\n case "correct": return 43\n case "programs": return 44\n case "easier": return 45\n case "developer.": return 46\n case "To": return 47\n case "achieve": return 48\n case "this": return 49\n case "goal,": return 50\n case "we": return 51\n case "believe": return 52\n case "that": return 53\n case "most": return 54\n case "obvious": return 55\n case "way": return 56\n case "write": return 57\n case "code": return 58\n case "must": return 59\n case "also": return 60\n case "be:": return 61\n case "Safe.": return 62\n case "should": return 63\n case "behave": return 64\n case "in": return 65\n case "safe": return 66\n case "manner.": return 67\n case "Undefined": return 68\n case "behavior": return 69\n case "enemy": return 70\n case "developer": return 71\n case "mistakes": return 72\n case "be": return 73\n case "caught": return 74\n case "before": return 75\n case "production.": return 76\n case "Opting": return 77\n case "safety": return 78\n case "sometimes": return 79\n case "means": return 80\n case "will": return 81\n case "feel": return 82\n case "strict,": return 83\n case "but": return 84\n case "clarity": return 85\n case "saves": return 86\n case "time": return 87\n case "long": return 88\n case "run.": return 89\n case "Fast.": return 90\n case "intended": return 91\n case "as": return 92\n case "replacement": return 93\n case "C-based": return 94\n case "languages": return 95\n case "(C, C++, Objective-C).": return 96\n case "As": return 97\n case "such,": return 98\n case "comparable": return 99\n case "those": return 100\n case "performance": return 101\n case "tasks.": return 102\n case "Performance": return 103\n case "predictable": return 104\n case "consistent,": return 105\n case "not": return 106\n case "just": return 107\n case "fast": return 108\n case "short": return 109\n case "bursts": return 110\n case "require": return 111\n case "clean-up": return 112\n case "later.": return 113\n case "There": return 114\n case "are": return 115\n case "lots": return 116\n case "with": return 117\n case "novel": return 118\n case "features": return 119\n case "x": return 120\n case "being": return 121\n case "rare.": return 122\n case "Expressive.": return 123\n case "benefits": return 124\n case "decades": return 125\n case "advancement": return 126\n case "computer": return 127\n case "science": return 128\n case "offer": return 129\n case "syntax": return 130\n case "joy": return 131\n case "use,": return 132\n case "developers": return 133\n case "expect.": return 134\n case "But": return 135\n case "never": return 136\n case "done.": return 137\n case "We": return 138\n case "monitor": return 139\n case "advancements": return 140\n case "embrace": return 141\n case "what": return 142\n case "works,": return 143\n case "continually": return 144\n case "evolving": return 145\n case "even": return 146\n case "better.": return 147\n case "Tools": return 148\n case "critical": return 149\n case "part": return 150\n case "ecosystem.": return 151\n case "strive": return 152\n case "integrate": return 153\n case "well": return 154\n case "within": return 155\n case "developerss": return 156\n case "toolset,": return 157\n case "build": return 158\n case "quickly,": return 159\n case "present": return 160\n case "excellent": return 161\n case "diagnostics,": return 162\n case "enable": return 163\n case "interactive": return 164\n case "development": return 165\n case "experiences.": return 166\n case "can": return 167\n case "so": return 168\n case "much": return 169\n case "more": return 170\n case "powerful,": return 171\n case "like": return 172\n case "Swift-based": return 173\n case "playgrounds": return 174\n case "do": return 175\n case "Xcode,": return 176\n case "or": return 177\n case "web-based": return 178\n case "REPL": return 179\n case "when": return 180\n case "working": return 181\n case "Linux": return 182\n case "server-side": return 183\n case "code.": return 184\n default: return -1\n }\n}\n\n@inline(never)\nfunc test(_ s: String) {\n blackHole(getIndex(s))\n}\n\n@inline(never)\npublic func run_StringSwitch(n: Int) {\n let first = "Swift"\n let short = "To"\n let long = "(C, C++, Objective-C)."\n let last = "code."\n let none = "non existent string"\n for _ in 1...100*n {\n test(first)\n test(short)\n test(long)\n test(last)\n test(none)\n }\n}\n\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringSwitch.swift | cpp_apple_swift_benchmark_single-source_StringSwitch.swift | Swift | 6,253 | 0.95 | 0.021368 | 0.048246 | vue-tools | 791 | 2025-01-02T15:36:16.858411 | MIT | false | f7c75775704daac819ec71421e3a0cb1 |
//===--- StringWalk.swift -------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to StringWalk.swift.gyb and run\n// scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\n//\n// Test String iteration performance over a variety of workloads, languages,\n// and symbols.\n//\n\nimport TestsUtils\n\n//\n// Helper functionality\n//\n\n@inline(never) func count_unicodeScalars(_ s: String.UnicodeScalarView) {\n var count = 0\n for _ in s {\n count += 1\n }\n blackHole(count)\n}\n@inline(never) func count_characters(_ s: String) {\n var count = 0\n for _ in s {\n count += 1\n }\n blackHole(count)\n}\n@inline(never) func count_unicodeScalars_rev(\n _ s: ReversedCollection<String.UnicodeScalarView>\n) {\n var count = 0\n for _ in s {\n count += 1\n }\n blackHole(count)\n}\n@inline(never) func count_characters_rev(\n _ s: ReversedCollection<String>\n) {\n var count = 0\n for _ in s {\n count += 1\n }\n blackHole(count)\n}\n\n//\n// Workloads\n//\nlet ascii =\n "siebenhundertsiebenundsiebzigtausendsiebenhundertsiebenundsiebzig"\nlet emoji = "👍👩👩👧👧👨👨👦👦🇺🇸🇨🇦🇲🇽👍🏻👍🏼👍🏽👍🏾👍🏿"\nlet utf16 = emoji + "the quick brown fox" + String(emoji.reversed())\n\nlet japanese = "今回のアップデートでSwiftに大幅な改良が施され、安定していてしかも直感的に使うことができるAppleプラットフォーム向けプログラミング言語になりました。"\nlet chinese = "Swift 是面向 Apple 平台的编程语言,功能强大且直观易用,而本次更新对其进行了全面优化。"\nlet korean = "이번 업데이트에서는 강력하면서도 직관적인 Apple 플랫폼용 프로그래밍 언어인 Swift를 완벽히 개선하였습니다."\nlet russian = "в чащах юга жил-был цитрус? да, но фальшивый экземпляр"\nlet punctuated = "\u{201c}Hello\u{2010}world\u{2026}\u{201d}"\nlet punctuatedJapanese = "\u{300c}\u{300e}今日は\u{3001}世界\u{3002}\u{300f}\u{300d}"\n\n// A workload that's mostly Latin characters, with occasional emoji\n// interspersed. Common for tweets.\nlet tweet = "Worst thing about working on String is that it breaks *everything*. Asserts, debuggers, and *especially* printf-style debugging 😭"\n\n//\n// Benchmarks\n//\n\n// Pre-commit benchmark: simple scalar walk\n@inline(never)\npublic func run_StringWalk(_ n: Int) {\n return run_StringWalk_ascii_unicodeScalars(n)\n}\n\n// Extended String benchmarks:\nlet baseMultiplier = 250\nlet unicodeScalarsMultiplier = baseMultiplier\nlet charactersMultiplier = baseMultiplier / 5\n\n\n// An extended benchmark suite exercising finer-granularity behavior of our\n// Strings.\npublic let benchmarks = [\n BenchmarkInfo(\n name: "StringWalk",\n runFunction: run_StringWalk,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_ascii_unicodeScalars",\n runFunction: run_StringWalk_ascii_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_ascii_characters",\n runFunction: run_StringWalk_ascii_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_ascii_unicodeScalars",\n runFunction: run_CharIteration_ascii_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_ascii_unicodeScalars",\n runFunction: run_CharIndexing_ascii_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_ascii_unicodeScalars_Backwards",\n runFunction: run_StringWalk_ascii_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_ascii_characters_Backwards",\n runFunction: run_StringWalk_ascii_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_ascii_unicodeScalars_Backwards",\n runFunction: run_CharIteration_ascii_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_ascii_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_ascii_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_utf16_unicodeScalars",\n runFunction: run_StringWalk_utf16_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_utf16_characters",\n runFunction: run_StringWalk_utf16_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_utf16_unicodeScalars",\n runFunction: run_CharIteration_utf16_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_utf16_unicodeScalars",\n runFunction: run_CharIndexing_utf16_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_utf16_unicodeScalars_Backwards",\n runFunction: run_StringWalk_utf16_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_utf16_characters_Backwards",\n runFunction: run_StringWalk_utf16_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_utf16_unicodeScalars_Backwards",\n runFunction: run_CharIteration_utf16_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_utf16_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_utf16_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_tweet_unicodeScalars",\n runFunction: run_StringWalk_tweet_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_tweet_characters",\n runFunction: run_StringWalk_tweet_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_tweet_unicodeScalars",\n runFunction: run_CharIteration_tweet_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_tweet_unicodeScalars",\n runFunction: run_CharIndexing_tweet_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_tweet_unicodeScalars_Backwards",\n runFunction: run_StringWalk_tweet_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_tweet_characters_Backwards",\n runFunction: run_StringWalk_tweet_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_tweet_unicodeScalars_Backwards",\n runFunction: run_CharIteration_tweet_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_tweet_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_tweet_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_japanese_unicodeScalars",\n runFunction: run_StringWalk_japanese_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_japanese_characters",\n runFunction: run_StringWalk_japanese_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_japanese_unicodeScalars",\n runFunction: run_CharIteration_japanese_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_japanese_unicodeScalars",\n runFunction: run_CharIndexing_japanese_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_japanese_unicodeScalars_Backwards",\n runFunction: run_StringWalk_japanese_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_japanese_characters_Backwards",\n runFunction: run_StringWalk_japanese_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_japanese_unicodeScalars_Backwards",\n runFunction: run_CharIteration_japanese_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_japanese_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_japanese_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_chinese_unicodeScalars",\n runFunction: run_StringWalk_chinese_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_chinese_characters",\n runFunction: run_StringWalk_chinese_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_chinese_unicodeScalars",\n runFunction: run_CharIteration_chinese_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_chinese_unicodeScalars",\n runFunction: run_CharIndexing_chinese_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_chinese_unicodeScalars_Backwards",\n runFunction: run_StringWalk_chinese_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_chinese_characters_Backwards",\n runFunction: run_StringWalk_chinese_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_chinese_unicodeScalars_Backwards",\n runFunction: run_CharIteration_chinese_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_chinese_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_chinese_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_korean_unicodeScalars",\n runFunction: run_StringWalk_korean_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_korean_characters",\n runFunction: run_StringWalk_korean_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_korean_unicodeScalars",\n runFunction: run_CharIteration_korean_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_korean_unicodeScalars",\n runFunction: run_CharIndexing_korean_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_korean_unicodeScalars_Backwards",\n runFunction: run_StringWalk_korean_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_korean_characters_Backwards",\n runFunction: run_StringWalk_korean_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_korean_unicodeScalars_Backwards",\n runFunction: run_CharIteration_korean_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_korean_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_korean_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_russian_unicodeScalars",\n runFunction: run_StringWalk_russian_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_russian_characters",\n runFunction: run_StringWalk_russian_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_russian_unicodeScalars",\n runFunction: run_CharIteration_russian_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_russian_unicodeScalars",\n runFunction: run_CharIndexing_russian_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_russian_unicodeScalars_Backwards",\n runFunction: run_StringWalk_russian_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_russian_characters_Backwards",\n runFunction: run_StringWalk_russian_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_russian_unicodeScalars_Backwards",\n runFunction: run_CharIteration_russian_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_russian_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_russian_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_punctuated_unicodeScalars",\n runFunction: run_StringWalk_punctuated_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_punctuated_characters",\n runFunction: run_StringWalk_punctuated_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_punctuated_unicodeScalars",\n runFunction: run_CharIteration_punctuated_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_punctuated_unicodeScalars",\n runFunction: run_CharIndexing_punctuated_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_punctuated_unicodeScalars_Backwards",\n runFunction: run_StringWalk_punctuated_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_punctuated_characters_Backwards",\n runFunction: run_StringWalk_punctuated_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_punctuated_unicodeScalars_Backwards",\n runFunction: run_CharIteration_punctuated_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_punctuated_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_punctuated_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_punctuatedJapanese_unicodeScalars",\n runFunction: run_StringWalk_punctuatedJapanese_unicodeScalars,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_punctuatedJapanese_characters",\n runFunction: run_StringWalk_punctuatedJapanese_characters,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_punctuatedJapanese_unicodeScalars",\n runFunction: run_CharIteration_punctuatedJapanese_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_punctuatedJapanese_unicodeScalars",\n runFunction: run_CharIndexing_punctuatedJapanese_unicodeScalars,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "StringWalk_punctuatedJapanese_unicodeScalars_Backwards",\n runFunction: run_StringWalk_punctuatedJapanese_unicodeScalars_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "StringWalk_punctuatedJapanese_characters_Backwards",\n runFunction: run_StringWalk_punctuatedJapanese_characters_Backwards,\n tags: [.api, .String, .skip],\n legacyFactor: 40),\n\n\n BenchmarkInfo(\n name: "CharIteration_punctuatedJapanese_unicodeScalars_Backwards",\n runFunction: run_CharIteration_punctuatedJapanese_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n\n BenchmarkInfo(\n name: "CharIndexing_punctuatedJapanese_unicodeScalars_Backwards",\n runFunction: run_CharIndexing_punctuatedJapanese_unicodeScalars_Backwards,\n tags: [.validation, .api, .String],\n legacyFactor: 40),\n]\n\n\n@inline(never)\npublic func run_StringWalk_ascii_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(ascii.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_ascii_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(ascii.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_ascii_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(ascii)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_ascii_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(ascii.reversed())\n }\n}\n\n\nlet asciiCharacters = Array(ascii)\n\n@inline(never)\npublic func run_CharIteration_ascii_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in asciiCharacters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_ascii_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in asciiCharacters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_ascii_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in asciiCharacters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_ascii_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in asciiCharacters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n@inline(never)\npublic func run_StringWalk_utf16_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(utf16.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_utf16_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(utf16.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_utf16_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(utf16)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_utf16_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(utf16.reversed())\n }\n}\n\n\nlet utf16Characters = Array(utf16)\n\n@inline(never)\npublic func run_CharIteration_utf16_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in utf16Characters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_utf16_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in utf16Characters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_utf16_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in utf16Characters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_utf16_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in utf16Characters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n@inline(never)\npublic func run_StringWalk_tweet_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(tweet.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_tweet_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(tweet.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_tweet_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(tweet)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_tweet_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(tweet.reversed())\n }\n}\n\n\nlet tweetCharacters = Array(tweet)\n\n@inline(never)\npublic func run_CharIteration_tweet_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in tweetCharacters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_tweet_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in tweetCharacters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_tweet_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in tweetCharacters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_tweet_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in tweetCharacters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n@inline(never)\npublic func run_StringWalk_japanese_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(japanese.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_japanese_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(japanese.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_japanese_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(japanese)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_japanese_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(japanese.reversed())\n }\n}\n\n\nlet japaneseCharacters = Array(japanese)\n\n@inline(never)\npublic func run_CharIteration_japanese_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in japaneseCharacters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_japanese_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in japaneseCharacters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_japanese_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in japaneseCharacters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_japanese_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in japaneseCharacters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n@inline(never)\npublic func run_StringWalk_chinese_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(chinese.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_chinese_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(chinese.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_chinese_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(chinese)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_chinese_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(chinese.reversed())\n }\n}\n\n\nlet chineseCharacters = Array(chinese)\n\n@inline(never)\npublic func run_CharIteration_chinese_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in chineseCharacters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_chinese_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in chineseCharacters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_chinese_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in chineseCharacters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_chinese_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in chineseCharacters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n@inline(never)\npublic func run_StringWalk_korean_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(korean.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_korean_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(korean.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_korean_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(korean)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_korean_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(korean.reversed())\n }\n}\n\n\nlet koreanCharacters = Array(korean)\n\n@inline(never)\npublic func run_CharIteration_korean_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in koreanCharacters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_korean_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in koreanCharacters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_korean_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in koreanCharacters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_korean_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in koreanCharacters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n@inline(never)\npublic func run_StringWalk_russian_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(russian.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_russian_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(russian.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_russian_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(russian)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_russian_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(russian.reversed())\n }\n}\n\n\nlet russianCharacters = Array(russian)\n\n@inline(never)\npublic func run_CharIteration_russian_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in russianCharacters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_russian_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in russianCharacters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_russian_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in russianCharacters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_russian_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in russianCharacters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n@inline(never)\npublic func run_StringWalk_punctuated_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(punctuated.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_punctuated_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(punctuated.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_punctuated_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(punctuated)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_punctuated_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(punctuated.reversed())\n }\n}\n\n\nlet punctuatedCharacters = Array(punctuated)\n\n@inline(never)\npublic func run_CharIteration_punctuated_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in punctuatedCharacters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_punctuated_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in punctuatedCharacters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_punctuated_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in punctuatedCharacters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_punctuated_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in punctuatedCharacters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n@inline(never)\npublic func run_StringWalk_punctuatedJapanese_unicodeScalars(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars(punctuatedJapanese.unicodeScalars)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_punctuatedJapanese_unicodeScalars_Backwards(_ n: Int) {\n for _ in 1...unicodeScalarsMultiplier*n {\n count_unicodeScalars_rev(punctuatedJapanese.unicodeScalars.reversed())\n }\n}\n\n\n@inline(never)\npublic func run_StringWalk_punctuatedJapanese_characters(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters(punctuatedJapanese)\n }\n}\n\n@inline(never)\npublic func run_StringWalk_punctuatedJapanese_characters_Backwards(_ n: Int) {\n for _ in 1...charactersMultiplier*n {\n count_characters_rev(punctuatedJapanese.reversed())\n }\n}\n\n\nlet punctuatedJapaneseCharacters = Array(punctuatedJapanese)\n\n@inline(never)\npublic func run_CharIteration_punctuatedJapanese_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in punctuatedJapaneseCharacters {\n for u in c.unicodeScalars {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIteration_punctuatedJapanese_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in punctuatedJapaneseCharacters {\n for u in c.unicodeScalars.reversed() {\n count |= Int(u.value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_punctuatedJapanese_unicodeScalars(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in punctuatedJapaneseCharacters {\n let s = c.unicodeScalars\n for i in s.indices {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n@inline(never)\npublic func run_CharIndexing_punctuatedJapanese_unicodeScalars_Backwards(_ n: Int) {\n var count = 0\n for _ in 1...unicodeScalarsMultiplier*n {\n for c in punctuatedJapaneseCharacters {\n let s = c.unicodeScalars\n for i in s.indices.reversed() {\n count |= Int(s[i].value)\n }\n }\n }\n blackHole(count)\n}\n\n\n\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StringWalk.swift | cpp_apple_swift_benchmark_single-source_StringWalk.swift | Swift | 35,300 | 0.95 | 0.109341 | 0.033599 | vue-tools | 851 | 2024-05-09T21:37:33.202076 | MIT | false | 3ac708674ced3040a2a051b4b9bcbb1d |
//===--- StrToInt.swift ---------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test checks performance of String to Int conversion.\n// It is reported to be very slow: <rdar://problem/17255477>\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "StrToInt",\n runFunction: run_StrToInt,\n tags: [.validation, .api, .String],\n legacyFactor: 10)\n\n@inline(never)\npublic func run_StrToInt(_ n: Int) {\n // 64 numbers from -500_000 to 500_000 generated randomly\n let input = ["-237392", "293715", "126809", "333779", "-362824", "144198",\n "-394973", "-163669", "-7236", "376965", "-400783", "-118670",\n "454728", "-38915", "136285", "-448481", "-499684", "68298",\n "382671", "105432", "-38385", "39422", "-267849", "-439886",\n "292690", "87017", "404692", "27692", "486408", "336482",\n "-67850", "56414", "-340902", "-391782", "414778", "-494338",\n "-413017", "-377452", "-300681", "170194", "428941", "-291665",\n "89331", "329496", "-364449", "272843", "-10688", "142542",\n "-417439", "167337", "96598", "-264104", "-186029", "98480",\n "-316727", "483808", "300149", "-405877", "-98938", "283685",\n "-247856", "-46975", "346060", "160085",]\n let ref_result = 517492\n func doOneIter(_ arr: [String]) -> Int {\n var r = 0\n for n in arr {\n r += Int(n)!\n }\n if r < 0 {\n r = -r\n }\n return r\n }\n var res = Int.max\n for _ in 1...100*n {\n res = res & doOneIter(input)\n }\n check(res == ref_result)\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_StrToInt.swift | cpp_apple_swift_benchmark_single-source_StrToInt.swift | Swift | 2,038 | 0.95 | 0.092593 | 0.27451 | awesome-app | 772 | 2025-02-22T14:11:49.677329 | BSD-3-Clause | false | 021ed72413b8ba28b4ed260d9a786b34 |
//===--- Suffix.swift -----------------------------------------*- swift -*-===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n////////////////////////////////////////////////////////////////////////////////\n// WARNING: This file is manually generated from .gyb template and should not\n// be directly modified. Instead, make changes to Suffix.swift.gyb and run\n// scripts/generate_harness/generate_harness.py to regenerate this file.\n////////////////////////////////////////////////////////////////////////////////\n\nimport TestsUtils\n\nlet sequenceCount = 4096\nlet suffixCount = 1024\nlet sumCount = suffixCount * (2 * sequenceCount - suffixCount - 1) / 2\nlet array: [Int] = Array(0..<sequenceCount)\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "SuffixCountableRange",\n runFunction: run_SuffixCountableRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixSequence",\n runFunction: run_SuffixSequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixAnySequence",\n runFunction: run_SuffixAnySequence,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixAnySeqCntRange",\n runFunction: run_SuffixAnySeqCntRange,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixAnySeqCRangeIter",\n runFunction: run_SuffixAnySeqCRangeIter,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixAnyCollection",\n runFunction: run_SuffixAnyCollection,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixArray",\n runFunction: run_SuffixArray,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n BenchmarkInfo(\n name: "SuffixCountableRangeLazy",\n runFunction: run_SuffixCountableRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixSequenceLazy",\n runFunction: run_SuffixSequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixAnySequenceLazy",\n runFunction: run_SuffixAnySequenceLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixAnySeqCntRangeLazy",\n runFunction: run_SuffixAnySeqCntRangeLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixAnySeqCRangeIterLazy",\n runFunction: run_SuffixAnySeqCRangeIterLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixAnyCollectionLazy",\n runFunction: run_SuffixAnyCollectionLazy,\n tags: [.validation, .api]),\n BenchmarkInfo(\n name: "SuffixArrayLazy",\n runFunction: run_SuffixArrayLazy,\n tags: [.validation, .api, .Array],\n setUpFunction: { blackHole(array) }),\n]\n\n@inline(never)\npublic func run_SuffixCountableRange(_ n: Int) {\n let s = 0..<sequenceCount\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixSequence(_ n: Int) {\n let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixAnySequence(_ n: Int) {\n let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixAnySeqCntRange(_ n: Int) {\n let s = AnySequence(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixAnySeqCRangeIter(_ n: Int) {\n let s = AnySequence((0..<sequenceCount).makeIterator())\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixAnyCollection(_ n: Int) {\n let s = AnyCollection(0..<sequenceCount)\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixArray(_ n: Int) {\n let s = array\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixCountableRangeLazy(_ n: Int) {\n let s = (0..<sequenceCount).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixSequenceLazy(_ n: Int) {\n let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixAnySequenceLazy(_ n: Int) {\n let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixAnySeqCntRangeLazy(_ n: Int) {\n let s = (AnySequence(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixAnySeqCRangeIterLazy(_ n: Int) {\n let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixAnyCollectionLazy(_ n: Int) {\n let s = (AnyCollection(0..<sequenceCount)).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n@inline(never)\npublic func run_SuffixArrayLazy(_ n: Int) {\n let s = (array).lazy\n for _ in 1...20*n {\n var result = 0\n for element in s.suffix(suffixCount) {\n result += element\n }\n check(result == sumCount)\n }\n}\n\n// Local Variables:\n// eval: (read-only-mode 1)\n// End:\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_Suffix.swift | cpp_apple_swift_benchmark_single-source_Suffix.swift | Swift | 6,753 | 0.95 | 0.122951 | 0.079832 | vue-tools | 539 | 2025-04-15T00:38:13.156464 | Apache-2.0 | false | f2d2e6035a9ff961759b05ee0c572810 |
//===--- SuperChars.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test tests the performance of ASCII Character comparison.\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "SuperChars2",\n runFunction: run_SuperChars,\n tags: [.validation, .api, .String],\n setUpFunction: { blackHole(alphabetInput) })\n\n// Permute some characters.\nlet alphabetInput: [Character] = [\n "A", "B", "C", "D", "E", "F", "«",\n "á", "お", "S", "T", "U", "🇯🇵",\n "🧟♀️", "👩👦👦", "🕴🏿", "2", "?",\n ]\n\n@inline(never)\npublic func run_SuperChars(_ n: Int) {\n // Permute some characters.\n let alphabet: [Character] = alphabetInput\n\n for _ in 0..<n {\n for firstChar in alphabet {\n for middleChar in alphabet {\n for lastChar in alphabet {\n blackHole((firstChar == middleChar) != (middleChar < lastChar))\n }\n }\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_SuperChars.swift | cpp_apple_swift_benchmark_single-source_SuperChars.swift | Swift | 1,359 | 0.95 | 0.136364 | 0.358974 | node-utils | 948 | 2024-01-21T15:48:33.755657 | GPL-3.0 | false | a8a73a2f418fbc2e45049154a26e0270 |
//===--- TwoSum.swift -----------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\n// This test is solves 2SUM problem:\n// Given an array and a number C, find elements A and B such that A+B = C\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "TwoSum",\n runFunction: run_TwoSum,\n tags: [.validation, .api, .Dictionary, .Array, .algorithm],\n legacyFactor: 2)\n\nlet array = [\n 959, 81, 670, 727, 416, 171, 401, 398, 707, 596, 200, 9, 414, 98, 43,\n 352, 752, 158, 593, 418, 240, 912, 542, 445, 429, 456, 993, 618, 52, 649,\n 759, 190, 126, 306, 966, 37, 787, 981, 606, 372, 597, 901, 158, 284, 809,\n 820, 173, 538, 644, 428, 932, 967, 962, 959, 233, 467, 220, 8, 729, 889,\n 277, 494, 554, 670, 91, 657, 606, 248, 644, 8, 366, 815, 567, 993, 696,\n 763, 800, 531, 301, 863, 680, 703, 279, 388, 871, 124, 302, 617, 410, 366,\n 813, 599, 543, 508, 336, 312, 212, 86, 524, 64, 641, 533, 207, 893, 146,\n 534, 104, 888, 534, 464, 423, 583, 365, 420, 642, 514, 336, 974, 846, 437,\n 604, 121, 180, 794, 278, 467, 818, 603, 537, 167, 169, 704, 9, 843, 555,\n 154, 598, 566, 676, 682, 828, 128, 875, 445, 918, 505, 393, 571, 3, 406,\n 719, 165, 505, 750, 396, 726, 404, 391, 532, 403, 728, 240, 89, 917, 665,\n 561, 282, 302, 438, 714, 6, 290, 939, 200, 788, 128, 773, 900, 934, 772,\n 130, 884, 60, 870, 812, 750, 349, 35, 155, 905, 595, 806, 771, 443, 304,\n 283, 404, 905, 861, 820, 338, 380, 709, 927, 42, 478, 789, 656, 106, 218,\n 412, 453, 262, 864, 701, 686, 770, 34, 624, 597, 843, 913, 966, 230, 942,\n 112, 991, 299, 669, 399, 630, 943, 934, 448, 62, 745, 917, 397, 440, 286,\n 875, 22, 989, 235, 732, 906, 923, 643, 853, 68, 48, 524, 86, 89, 688,\n 224, 546, 73, 963, 755, 413, 524, 680, 472, 19, 996, 81, 100, 338, 626,\n 911, 358, 887, 242, 159, 731, 494, 985, 83, 597, 98, 270, 909, 828, 988,\n 684, 622, 499, 932, 299, 449, 888, 533, 801, 844, 940, 642, 501, 513, 735,\n 674, 211, 394, 635, 372, 213, 618, 280, 792, 487, 605, 755, 584, 163, 358,\n 249, 784, 153, 166, 685, 264, 457, 677, 824, 391, 830, 310, 629, 591, 62,\n 265, 373, 195, 803, 756, 601, 592, 843, 184, 220, 155, 396, 828, 303, 553,\n 778, 477, 735, 430, 93, 464, 306, 579, 828, 759, 809, 916, 759, 336, 926,\n 776, 111, 746, 217, 585, 441, 928, 236, 959, 417, 268, 200, 231, 181, 228,\n 627, 675, 814, 534, 90, 665, 1, 604, 479, 598, 109, 370, 719, 786, 700,\n 591, 536, 7, 147, 648, 864, 162, 404, 536, 768, 175, 517, 394, 14, 945,\n 865, 490, 630, 963, 49, 904, 277, 16, 349, 301, 840, 817, 590, 738, 357,\n 199, 581, 601, 33, 659, 951, 640, 126, 302, 632, 265, 894, 892, 587, 274,\n 487, 499, 789, 954, 652, 825, 512, 170, 882, 269, 471, 571, 185, 364, 217,\n 427, 38, 715, 950, 808, 270, 746, 830, 501, 264, 581, 211, 466, 970, 395,\n 610, 930, 885, 696, 568, 920, 487, 764, 896, 903, 241, 894, 773, 896, 341,\n 126, 22, 420, 959, 691, 207, 745, 126, 873, 341, 166, 127, 108, 426, 497,\n 681, 796, 430, 367, 363\n]\n\n@inline(never)\npublic func run_TwoSum(_ n: Int) {\n var i1: Int?\n var i2: Int?\n var dict: Dictionary<Int, Int> = [:]\n for _ in 1...n {\n for sum in 500..<600 {\n dict = [:]\n i1 = nil\n i2 = nil\n for n in 0..<array.count {\n if let m = dict[sum - array[n]] {\n i1 = m\n i2 = n\n break\n }\n dict[array[n]] = n\n }\n check(i1 != nil && i2 != nil)\n check(sum == array[i1!] + array[i2!])\n }\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_TwoSum.swift | cpp_apple_swift_benchmark_single-source_TwoSum.swift | Swift | 3,884 | 0.95 | 0.072289 | 0.164557 | vue-tools | 293 | 2025-02-07T19:03:14.359745 | Apache-2.0 | false | 83735da079b6cb16defb15b1665e775c |
//===--- TypeFlood.swift --------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n//\n// We use this test to benchmark the runtime memory that Swift programs use.\n//\n// The Swift compiler caches the metadata that it needs to generate to support\n// code that checks for protocol conformance and other operations that require\n// use of metadata.\n// This mechanism has the potential to allocate a lot of memory. This benchmark\n// program generates 2^15 calls to swift_conformsToProtocol and fills the\n// metadata/conformance caches with data that we never free. We use this\n// program to track the runtime memory usage of swift programs. The test is\n// optimized away in Release builds but kept in Debug mode.\n\n\nimport TestsUtils\n\npublic let benchmarks =\n BenchmarkInfo(\n name: "TypeFlood",\n runFunction: run_TypeFlood,\n tags: [.validation, .metadata])\n\nprotocol Pingable {}\n\nstruct Some1<T> {\n init() {}\n func foo(_ x: T) {}\n}\nstruct Some0<T> {\n init() {}\n func foo(_ x: T) {}\n}\n\n@inline(never)\nfunc flood<T>(_ x: T) {\n _ = Some1<Some1<Some1<Some1<T>>>>() is Pingable\n _ = Some1<Some1<Some1<Some0<T>>>>() is Pingable\n _ = Some1<Some1<Some0<Some1<T>>>>() is Pingable\n _ = Some1<Some1<Some0<Some0<T>>>>() is Pingable\n _ = Some1<Some0<Some1<Some1<T>>>>() is Pingable\n _ = Some1<Some0<Some1<Some0<T>>>>() is Pingable\n _ = Some1<Some0<Some0<Some1<T>>>>() is Pingable\n _ = Some1<Some0<Some0<Some0<T>>>>() is Pingable\n _ = Some0<Some1<Some1<Some1<T>>>>() is Pingable\n _ = Some0<Some1<Some1<Some0<T>>>>() is Pingable\n _ = Some0<Some1<Some0<Some1<T>>>>() is Pingable\n _ = Some0<Some1<Some0<Some0<T>>>>() is Pingable\n _ = Some0<Some0<Some1<Some1<T>>>>() is Pingable\n _ = Some0<Some0<Some1<Some0<T>>>>() is Pingable\n _ = Some0<Some0<Some0<Some1<T>>>>() is Pingable\n _ = Some0<Some0<Some0<Some0<T>>>>() is Pingable\n}\n\n@inline(never)\nfunc flood3<T>(_ x: T) {\n flood(Some1<Some1<Some1<Some1<T>>>>())\n flood(Some1<Some1<Some1<Some0<T>>>>())\n flood(Some1<Some1<Some0<Some1<T>>>>())\n flood(Some1<Some1<Some0<Some0<T>>>>())\n flood(Some1<Some0<Some1<Some1<T>>>>())\n flood(Some1<Some0<Some1<Some0<T>>>>())\n flood(Some1<Some0<Some0<Some1<T>>>>())\n flood(Some1<Some0<Some0<Some0<T>>>>())\n flood(Some0<Some1<Some1<Some1<T>>>>())\n flood(Some0<Some1<Some1<Some0<T>>>>())\n flood(Some0<Some1<Some0<Some1<T>>>>())\n flood(Some0<Some1<Some0<Some0<T>>>>())\n flood(Some0<Some0<Some1<Some1<T>>>>())\n flood(Some0<Some0<Some1<Some0<T>>>>())\n flood(Some0<Some0<Some0<Some1<T>>>>())\n flood(Some0<Some0<Some0<Some0<T>>>>())\n}\n\n@inline(never)\nfunc flood2<T>(_ x: T) {\n flood3(Some1<Some1<Some1<Some1<T>>>>())\n flood3(Some1<Some1<Some1<Some0<T>>>>())\n flood3(Some1<Some1<Some0<Some1<T>>>>())\n flood3(Some1<Some1<Some0<Some0<T>>>>())\n flood3(Some1<Some0<Some1<Some1<T>>>>())\n flood3(Some1<Some0<Some1<Some0<T>>>>())\n flood3(Some1<Some0<Some0<Some1<T>>>>())\n flood3(Some1<Some0<Some0<Some0<T>>>>())\n flood3(Some0<Some1<Some1<Some1<T>>>>())\n flood3(Some0<Some1<Some1<Some0<T>>>>())\n flood3(Some0<Some1<Some0<Some1<T>>>>())\n flood3(Some0<Some1<Some0<Some0<T>>>>())\n flood3(Some0<Some0<Some1<Some1<T>>>>())\n flood3(Some0<Some0<Some1<Some0<T>>>>())\n flood3(Some0<Some0<Some0<Some1<T>>>>())\n flood3(Some0<Some0<Some0<Some0<T>>>>())\n}\n\n@inline(never)\npublic func run_TypeFlood(_ n: Int) {\n\n for _ in 1...n {\n flood3(Some1<Some1<Some1<Int>>>())\n flood3(Some1<Some1<Some0<Int>>>())\n flood3(Some1<Some0<Some1<Int>>>())\n flood3(Some1<Some0<Some0<Int>>>())\n flood3(Some0<Some1<Some1<Int>>>())\n flood3(Some0<Some1<Some0<Int>>>())\n flood3(Some0<Some0<Some1<Int>>>())\n flood3(Some0<Some0<Some0<Int>>>())\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_TypeFlood.swift | cpp_apple_swift_benchmark_single-source_TypeFlood.swift | Swift | 4,043 | 0.95 | 0.034188 | 0.205607 | vue-tools | 444 | 2025-05-12T19:53:39.267258 | GPL-3.0 | false | ced369dc3f5ef60ae0bc51ca65ac8872 |
//===--- UTF16Decode.swift -------------------------------------------------===//\n//\n// This source file is part of the Swift.org open source project\n//\n// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors\n// Licensed under Apache License v2.0 with Runtime Library Exception\n//\n// See https://swift.org/LICENSE.txt for license information\n// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors\n//\n//===----------------------------------------------------------------------===//\n\nimport TestsUtils\nimport Foundation\n\npublic let benchmarks = [\n BenchmarkInfo(\n name: "UTF16Decode",\n runFunction: run_UTF16Decode,\n tags: [.validation, .api, .String],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initFromCustom.cont",\n runFunction: run_UTF16Decode_InitFromCustom_contiguous,\n tags: [.validation, .api, .String],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initFromCustom.cont.ascii",\n runFunction: run_UTF16Decode_InitFromCustom_contiguous_ascii,\n tags: [.validation, .api, .String, .skip],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initFromCustom.noncont",\n runFunction: run_UTF16Decode_InitFromCustom_noncontiguous,\n tags: [.validation, .api, .String],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initFromCustom.noncont.ascii",\n runFunction: run_UTF16Decode_InitFromCustom_noncontiguous_ascii,\n tags: [.validation, .api, .String, .skip],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initFromData",\n runFunction: run_UTF16Decode_InitFromData,\n tags: [.validation, .api, .String],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initDecoding",\n runFunction: run_UTF16Decode_InitDecoding,\n tags: [.validation, .api, .String],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initFromData.ascii",\n runFunction: run_UTF16Decode_InitFromData_ascii,\n tags: [.validation, .api, .String, .skip],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initDecoding.ascii",\n runFunction: run_UTF16Decode_InitDecoding_ascii,\n tags: [.validation, .api, .String, .skip],\n setUpFunction: setUp),\n BenchmarkInfo(\n name: "UTF16Decode.initFromData.asciiAsAscii",\n runFunction: run_UTF16Decode_InitFromData_ascii_as_ascii,\n tags: [.validation, .api, .String, .skip],\n setUpFunction: setUp),\n]\n\ntypealias CodeUnit = UInt16\n\n// 1-byte sequences\n// This test case is the longest as it's the most performance sensitive.\nlet ascii = "Swift is a multi-paradigm, compiled programming language created for iOS, OS X, watchOS, tvOS and Linux development by Apple Inc. Swift is designed to work with Apple's Cocoa and Cocoa Touch frameworks and the large body of existing Objective-C code written for Apple products. Swift is intended to be more resilient to erroneous code (\"safer\") than Objective-C and also more concise. It is built with the LLVM compiler framework included in Xcode 6 and later and uses the Objective-C runtime, which allows C, Objective-C, C++ and Swift code to run within a single program."\nlet asciiCodeUnits: [CodeUnit] = Array(ascii.utf16)\nlet asciiData: Data = asciiCodeUnits.withUnsafeBytes { Data($0) }\n\n// 2-byte sequences\nlet russian = "Ру́сский язы́к один из восточнославянских языков, национальный язык русского народа."\n// 3-byte sequences\nlet japanese = "日本語(にほんご、にっぽんご)は、主に日本国内や日本人同士の間で使われている言語である。"\n// 4-byte sequences\n// Most commonly emoji, which are usually mixed with other text.\nlet emoji = "Panda 🐼, Dog 🐶, Cat 🐱, Mouse 🐭."\n\nlet allStrings: [[CodeUnit]] = [ascii, russian, japanese, emoji].map { Array($0.utf16) }\nlet allStringsCodeUnits: [CodeUnit] = Array(allStrings.joined())\nlet allStringsData: Data = allStringsCodeUnits.withUnsafeBytes { Data($0) }\n\nfunc setUp() {\n blackHole(asciiCodeUnits)\n blackHole(asciiData)\n blackHole(allStrings)\n blackHole(allStringsCodeUnits)\n blackHole(allStringsData)\n blackHole(allStringsCustomContiguous)\n blackHole(asciiCustomContiguous)\n blackHole(allStringsCustomNoncontiguous)\n blackHole(asciiCustomNoncontiguous)\n}\n\n@inline(never)\npublic func run_UTF16Decode(_ N: Int) {\n func isEmpty(_ result: UnicodeDecodingResult) -> Bool {\n switch result {\n case .emptyInput:\n return true\n default:\n return false\n }\n }\n\n for _ in 1...200*N {\n for string in allStrings {\n var it = string.makeIterator()\n var utf16 = UTF16()\n while !isEmpty(utf16.decode(&it)) { }\n }\n }\n}\n\n@inline(never)\npublic func run_UTF16Decode_InitFromData(_ N: Int) {\n for _ in 0..<200*N {\n blackHole(String(data: allStringsData, encoding: .utf16))\n }\n}\n\n@inline(never)\npublic func run_UTF16Decode_InitDecoding(_ N: Int) {\n for _ in 0..<2*N {\n blackHole(String(decoding: allStringsCodeUnits, as: UTF16.self))\n }\n}\n\n@inline(never)\npublic func run_UTF16Decode_InitFromData_ascii(_ N: Int) {\n for _ in 0..<100*N {\n blackHole(String(data: asciiData, encoding: .utf16))\n }\n}\n\n@inline(never)\npublic func run_UTF16Decode_InitDecoding_ascii(_ N: Int) {\n for _ in 0..<N {\n blackHole(String(decoding: asciiCodeUnits, as: UTF16.self))\n }\n}\n\n@inline(never)\npublic func run_UTF16Decode_InitFromData_ascii_as_ascii(_ N: Int) {\n for _ in 0..<1_000*N {\n blackHole(String(data: asciiData, encoding: .ascii))\n }\n}\n\nstruct CustomContiguousCollection: Collection {\n let storage: [CodeUnit]\n typealias Index = Int\n typealias Element = CodeUnit\n\n init(_ codeUnits: [CodeUnit]) { self.storage = codeUnits }\n subscript(position: Int) -> Element { self.storage[position] }\n var startIndex: Index { 0 }\n var endIndex: Index { storage.count }\n func index(after i: Index) -> Index { i+1 }\n\n @inline(never)\n func withContiguousStorageIfAvailable<R>(\n _ body: (UnsafeBufferPointer<CodeUnit>) throws -> R\n ) rethrows -> R? {\n try storage.withContiguousStorageIfAvailable(body)\n }\n}\nstruct CustomNoncontiguousCollection: Collection {\n let storage: [CodeUnit]\n typealias Index = Int\n typealias Element = CodeUnit\n\n init(_ codeUnits: [CodeUnit]) { self.storage = codeUnits }\n subscript(position: Int) -> Element { self.storage[position] }\n var startIndex: Index { 0 }\n var endIndex: Index { storage.count }\n func index(after i: Index) -> Index { i+1 }\n\n @inline(never)\n func withContiguousStorageIfAvailable<R>(\n _ body: (UnsafeBufferPointer<UInt8>) throws -> R\n ) rethrows -> R? {\n nil\n }\n}\nlet allStringsCustomContiguous = CustomContiguousCollection(allStringsCodeUnits)\nlet asciiCustomContiguous = CustomContiguousCollection(Array(ascii.utf16))\nlet allStringsCustomNoncontiguous = CustomNoncontiguousCollection(allStringsCodeUnits)\nlet asciiCustomNoncontiguous = CustomNoncontiguousCollection(Array(ascii.utf16))\n\n@inline(never)\npublic func run_UTF16Decode_InitFromCustom_contiguous(_ N: Int) {\n for _ in 0..<20*N {\n blackHole(String(decoding: allStringsCustomContiguous, as: UTF16.self))\n }\n}\n\n@inline(never)\npublic func run_UTF16Decode_InitFromCustom_contiguous_ascii(_ N: Int) {\n for _ in 0..<10*N {\n blackHole(String(decoding: asciiCustomContiguous, as: UTF16.self))\n }\n}\n\n@inline(never)\npublic func run_UTF16Decode_InitFromCustom_noncontiguous(_ N: Int) {\n for _ in 0..<20*N {\n blackHole(String(decoding: allStringsCustomNoncontiguous, as: UTF16.self))\n }\n}\n\n@inline(never)\npublic func run_UTF16Decode_InitFromCustom_noncontiguous_ascii(_ N: Int) {\n for _ in 0..<10*N {\n blackHole(String(decoding: asciiCustomNoncontiguous, as: UTF16.self))\n }\n}\n | dataset_sample\swift\swift\cpp_apple_swift_benchmark_single-source_UTF16Decode.swift | cpp_apple_swift_benchmark_single-source_UTF16Decode.swift | Swift | 7,843 | 0.95 | 0.080717 | 0.085 | python-kit | 703 | 2024-05-15T07:55:59.463495 | Apache-2.0 | false | 8b5b0dc1f6fe47e08ea824be4d1ab00b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.