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