xref: /llvm-project/llvm/lib/Support/ExponentialBackoff.cpp (revision edff3ff4d37a9e051e33146393b064ce987af252)
1*edff3ff4SMichael Spencer //===- llvm/Support/ExponentialBackoff.h ------------------------*- C++ -*-===//
2*edff3ff4SMichael Spencer //
3*edff3ff4SMichael Spencer // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*edff3ff4SMichael Spencer // See https://llvm.org/LICENSE.txt for license information.
5*edff3ff4SMichael Spencer // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*edff3ff4SMichael Spencer //
7*edff3ff4SMichael Spencer //===----------------------------------------------------------------------===//
8*edff3ff4SMichael Spencer 
9*edff3ff4SMichael Spencer #include "llvm/Support/ExponentialBackoff.h"
10*edff3ff4SMichael Spencer #include <thread>
11*edff3ff4SMichael Spencer 
12*edff3ff4SMichael Spencer using namespace llvm;
13*edff3ff4SMichael Spencer 
waitForNextAttempt()14*edff3ff4SMichael Spencer bool ExponentialBackoff::waitForNextAttempt() {
15*edff3ff4SMichael Spencer   auto Now = std::chrono::steady_clock::now();
16*edff3ff4SMichael Spencer   if (Now >= EndTime)
17*edff3ff4SMichael Spencer     return false;
18*edff3ff4SMichael Spencer 
19*edff3ff4SMichael Spencer   duration CurMaxWait = std::min(MinWait * CurrentMultiplier, MaxWait);
20*edff3ff4SMichael Spencer   std::uniform_int_distribution<uint64_t> Dist(MinWait.count(),
21*edff3ff4SMichael Spencer                                                CurMaxWait.count());
22*edff3ff4SMichael Spencer   // Use random_device directly instead of a PRNG as uniform_int_distribution
23*edff3ff4SMichael Spencer   // often only takes a few samples anyway.
24*edff3ff4SMichael Spencer   duration WaitDuration = std::min(duration(Dist(RandDev)), EndTime - Now);
25*edff3ff4SMichael Spencer   if (CurMaxWait < MaxWait)
26*edff3ff4SMichael Spencer     CurrentMultiplier *= 2;
27*edff3ff4SMichael Spencer   std::this_thread::sleep_for(WaitDuration);
28*edff3ff4SMichael Spencer   return true;
29*edff3ff4SMichael Spencer }
30