If someone has troubles with long HKStatisticsCollectionQuery request performing (dozens of seconds or minutes) please consider you have set proper dates for your predicate and anchor. The problem is a lot of data that HealthKit should calculate.
For example your goal is gathering data for today:
let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate)
let query = HKStatisticsCollectionQuery(quantityType: quantityType,
quantitySamplePredicate: predicate,
options: .cumulativeSum,
anchorDate: anchorDate,
intervalComponents: interval)
Here startDate is today's beginning, endDate is beginning for tomorrow, anchorDate is some day's beginning - in my case it's equal to endDate.
Important notice: if you pass nil instead of predicate, HealthKit will gather all data since the beginning and waste your time as a result.
Why tomorrow's beginning is necessary as endDate? The reason is statisticsUpdateHandler. Since you have decided to listen to data updates in HealthKit, predicate's end date should be in a future, not Date(). If you don't want to use statisticsUpdateHandler you can set endDate as now.