Coverage Report

Created: 2026-11-22 14:19

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/home/runner/work/charm/charm/src/ck-ldb/LBManager.C
Line
Count
Source
1
/**
2
 * \addtogroup CkLdb
3
 */
4
/*@{*/
5
6
#include "converse.h"
7
#include <charm++.h>
8
#include <ck.h>
9
#include "cksyncbarrier.h"
10
11
#include "DistributedLB.h"
12
#include "LBManager.h"
13
#include "ckcallback-ccs.h"
14
15
void LBObjLoadsCcsHandler(char* msg);
16
#include "LBSimulation.h"
17
#include "TreeLB.h"
18
#include "topology.h"
19
20
#include "json.hpp"
21
22
CkGroupID _lbmgr;
23
24
CkpvDeclare(LBUserDataLayout, lbobjdatalayout);
25
CkpvDeclare(int, _lb_obj_index);
26
27
CkpvDeclare(bool, lbmanagerInited); /**< true if lbdatabase is inited */
28
29
extern int quietModeRequested;
30
31
// command line options
32
CkLBArgs _lb_args;
33
bool _lb_predict = false;
34
int _lb_predict_delay = 10;
35
int _lb_predict_window = 20;
36
bool _lb_psizer_on = false;
37
38
0
SystemLoad::SystemLoad() {
39
0
  auto *activeRec = CkActiveLocRec();
40
0
  lbmgr = LBManagerObj();
41
0
  if (lbmgr && activeRec) {
42
0
    const LDObjHandle &runObj = activeRec->getLdHandle();
43
0
    lbmgr->ObjectStop(runObj);
44
0
  }
45
0
}
46
47
// registry class stores all load balancers linked and created at runtime
48
class LBDBRegistry
49
{
50
  friend class LBMgrInit;
51
  friend class LBManager;
52
53
 private:
54
  // table for all available LBs linked in
55
  struct LBDBEntry
56
  {
57
    std::string name;
58
    LBCreateFn cfn;
59
    LBAllocFn afn;
60
    std::string help;
61
    bool shown;  // if false, do not show in help page
62
0
    LBDBEntry() : name(""), cfn(0), afn(0), help(""), shown(true) {}
63
0
    LBDBEntry(int) {}
64
    LBDBEntry(std::string n, LBCreateFn cf, LBAllocFn af, std::string h, bool show = true)
65
3.34k
        : name(n), cfn(cf), afn(af), help(h), shown(show){};
66
  };
67
  std::vector<LBDBEntry> lbtables;       // a list of available LBs linked
68
  std::vector<const char*> compile_lbs;  // load balancers at compile time
69
  std::vector<const char*> runtime_lbs;  // load balancers at run time
70
  // map of {index in runtime_lbs, name of legacy LB to instantiate TreeLB with}
71
  // for use with the legacy LBs (e.g. GreedyLB -> the predefined Greedy version of TreeLB)
72
  std::unordered_map<int, const char*> legacy_runtime_treelbs;
73
 public:
74
1.37k
  LBDBRegistry() {}
75
  void displayLBs()
76
0
  {
77
0
    CmiPrintf("\nAvailable load balancers:\n");
78
0
    for (const auto& entry : lbtables)
79
0
    {
80
0
      if (entry.shown) CmiPrintf("* %s:\t%s\n", entry.name.c_str(), entry.help.c_str());
81
0
    }
82
0
    CmiPrintf("\n");
83
0
  }
84
  void addEntry(std::string name, LBCreateFn fn, LBAllocFn afn, std::string help,
85
                bool shown)
86
3.34k
  {
87
3.34k
    lbtables.emplace_back(name, fn, afn, help, shown);
88
3.34k
  }
89
0
  void addCompiletimeBalancer(const char* name) { compile_lbs.push_back(name); }
90
  void addRuntimeBalancer(const char* name, const char* legacyLBName = nullptr)
91
380
  {
92
380
    if (legacyLBName != nullptr)
93
309
    {
94
309
      legacy_runtime_treelbs.emplace((int)runtime_lbs.size(), legacyLBName);
95
309
    }
96
97
380
    runtime_lbs.push_back(name);
98
380
  }
99
  LBCreateFn search(std::string name)
100
254
  {
101
254
    const auto index = name.find_first_of(":,");
102
356
    for (int i = 0; i < lbtables.size(); i++)
103
356
      if (0 == lbtables[i].name.compare(0, index, name))
104
254
        return lbtables[i].cfn;
105
0
    return nullptr;
106
254
  }
107
  LBAllocFn getLBAllocFn(std::string name)
108
0
  {
109
0
    const auto index = name.find_first_of(":,");
110
0
    for (int i = 0; i < lbtables.size(); i++)
111
0
      if (0 == lbtables[i].name.compare(0, index, name))
112
0
        return lbtables[i].afn;
113
0
    return nullptr;
114
0
  }
115
};
116
117
static LBDBRegistry lbRegistry;
118
static std::vector<std::string> lbNames;
119
120
0
void LBDefaultCreate(const char* lbname) { lbRegistry.addCompiletimeBalancer(lbname); }
121
122
// default is to show the helper
123
void LBRegisterBalancer(std::string name, LBCreateFn fn, LBAllocFn afn, std::string help,
124
                        bool shown)
125
3.34k
{
126
3.34k
  lbRegistry.addEntry(name, fn, afn, help, shown);
127
3.34k
}
128
129
0
LBAllocFn getLBAllocFn(const char* lbname) { return lbRegistry.getLBAllocFn(lbname); }
130
131
// create a load balancer group using the strategy name
132
static void createLoadBalancer(const std::string& lbname, const char* legacybalancer = nullptr)
133
254
{
134
254
  LBCreateFn fn = lbRegistry.search(lbname);
135
254
  if (!fn)
136
0
  {  // invalid lb name
137
0
    CmiPrintf("Abort: Unknown load balancer: '%s'!\n", lbname.c_str());
138
0
    lbRegistry.displayLBs();  // display help page
139
0
    if(lbname == "help")
140
0
      CkExit(0);
141
0
    else
142
0
      CkExit(1);
143
0
  }
144
  // invoke function to create load balancer
145
254
  int seqno = LBManagerObj()->getLoadbalancerTicket();
146
254
  fn(CkLBOptions(seqno, legacybalancer));
147
254
}
148
149
// mainchare
150
LBMgrInit::LBMgrInit(CkArgMsg* m)
151
910
{
152
910
#if CMK_LBDB_ON
153
910
  _lbmgr = CProxy_LBManager::ckNew();
154
155
  // runtime specified load balancer
156
910
  if (!lbRegistry.runtime_lbs.empty())
157
248
  {
158
502
    for (int i = 0; i < lbRegistry.runtime_lbs.size(); i++)
159
254
    {
160
      // If this is a legacy TreeLB, pass in the legacy LB name
161
254
      const char* legacybalancer = lbRegistry.legacy_runtime_treelbs.count(i) > 0
162
254
                                       ? lbRegistry.legacy_runtime_treelbs[i]
163
254
                                       : nullptr;
164
254
      createLoadBalancer(lbRegistry.runtime_lbs[i], legacybalancer);
165
254
    }
166
248
  }
167
662
  else if (!lbRegistry.compile_lbs.empty())
168
0
  {
169
0
    for (const auto& balancer : lbRegistry.compile_lbs)
170
0
    {
171
0
      createLoadBalancer(balancer);
172
0
    }
173
0
  }
174
175
  // simulation mode
176
910
  if (LBSimulation::doSimulation)
177
2
  {
178
2
    CmiPrintf("Charm++> Entering Load Balancer Simulation Mode ... \n");
179
2
    CProxy_LBManager(_lbmgr).ckLocalBranch()->StartLB();
180
2
  }
181
910
#endif
182
910
  delete m;
183
910
}
184
185
// called from init.C
186
void _loadbalancerInit()
187
3.01k
{
188
3.01k
  CkpvInitialize(bool, lbmanagerInited);
189
3.01k
  CkpvAccess(lbmanagerInited) = false;
190
191
3.01k
  CkpvInitialize(LBUserDataLayout, lbobjdatalayout);
192
3.01k
  CkpvInitialize(int, _lb_obj_index);
193
3.01k
  CkpvAccess(_lb_obj_index) = -1;
194
195
3.01k
  char** argv = CkGetArgv();
196
3.01k
  char* balancer = NULL;
197
3.01k
  CmiArgGroup("Charm++", "Load Balancer");
198
199
3.01k
  CmiGetArgStringDesc(argv, "+TreeLBFile", &_lb_args.treeLBFile(), "TreeLB config file");
200
201
  // turn on MetaBalancer if set
202
3.01k
  _lb_args.metaLbOn() = CmiGetArgFlagDesc(argv, "+MetaLB", "Turn on MetaBalancer");
203
3.01k
  CmiGetArgStringDesc(argv, "+MetaLBModelDir", &_lb_args.metaLbModelDir(),
204
3.01k
                      "Use this directory to read model for MetaLB");
205
206
3.01k
  if (_lb_args.metaLbOn() && _lb_args.metaLbModelDir() != nullptr)
207
8
  {
208
8
#if CMK_USE_ZLIB
209
8
    if (CkMyRank() == 0)
210
3
    {
211
3
      lbRegistry.addRuntimeBalancer("TreeLB");
212
3
      lbNames.push_back("Greedy");
213
3
      lbNames.push_back("GreedyRefine");
214
3
      lbNames.push_back("DistributedLB");
215
3
      lbNames.push_back("RefineA");
216
3
      lbNames.push_back("Hybrid");
217
3
      lbNames.push_back("MetisLB");
218
3
      if (CkMyPe() == 0)
219
2
      {
220
2
        if (CmiGetArgStringDesc(argv, "+balancer", &balancer, "Use this load balancer"))
221
0
          CkPrintf(
222
0
              "Warning: Ignoring the +balancer option, since Meta-Balancer's model-based "
223
0
              "load balancer selection is enabled.\n");
224
2
        CkPrintf(
225
2
            "Warning: Automatic strategy selection in MetaLB is activated. This is an "
226
2
            "experimental feature.\n");
227
2
      }
228
3
      while (CmiGetArgStringDesc(argv, "+balancer", &balancer, "Use this load balancer"))
229
0
        ;
230
3
    }
231
#else
232
    if (CkMyPe() == 0)
233
      CkAbort(
234
          "MetaLB random forest model not supported because Charm++ was built without "
235
          "zlib support.\n");
236
#endif
237
8
  }
238
3.00k
  else
239
3.00k
  {
240
3.00k
    if (CkMyPe() == 0 && _lb_args.metaLbOn())
241
6
      CkPrintf(
242
6
          "Warning: MetaLB is activated. For Automatic strategy selection in MetaLB, "
243
6
          "pass directory of model files using +MetaLBModelDir.\n");
244
3.00k
    if (CkMyRank() == 0)
245
1.37k
    {
246
1.74k
      while (CmiGetArgStringDesc(argv, "+balancer", &balancer, "Use this load balancer"))
247
377
      {
248
377
        bool isLegacyTreeLB = true;
249
377
        const char* legacyBalancer;
250
377
        if (strcmp(balancer, "GreedyLB") == 0)
251
77
          legacyBalancer = "Greedy";
252
300
        else if (strcmp(balancer, "GreedyRefineLB") == 0)
253
18
          legacyBalancer = "GreedyRefine";
254
282
        else if (strcmp(balancer, "RefineLB") == 0)
255
21
          legacyBalancer = "RefineA";
256
261
        else if (strcmp(balancer, "RandCentLB") == 0)
257
51
          legacyBalancer = "Random";
258
210
        else if (strcmp(balancer, "DummyLB") == 0)
259
9
          legacyBalancer = "Dummy";
260
201
        else if (strcmp(balancer, "RotateLB") == 0)
261
133
          legacyBalancer = "Rotate";
262
68
        else
263
68
        {
264
68
          lbRegistry.addRuntimeBalancer(balancer); /* lbRegistry is a static */
265
68
          isLegacyTreeLB = false;
266
68
        }
267
268
377
        if (isLegacyTreeLB)
269
309
        {
270
309
          lbRegistry.addRuntimeBalancer("TreeLB", legacyBalancer);
271
309
        }
272
377
      }
273
1.37k
    }
274
1.63k
    else
275
1.63k
    {
276
      // For other ranks, consume the +balancer arguments to avoid spuriously
277
      // passing them to the application
278
2.11k
      while (CmiGetArgStringDesc(argv, "+balancer", &balancer, "Use this load balancer"))
279
482
        ;
280
1.63k
    }
281
3.00k
  }
282
283
3.01k
  CmiGetArgDoubleDesc(
284
3.01k
      argv, "+DistLBTargetRatio", &_lb_args.targetRatio(),
285
3.01k
      "The max/avg load ratio that DistributedLB will attempt to achieve");
286
3.01k
  CmiGetArgIntDesc(argv, "+DistLBMaxPhases", &_lb_args.maxDistPhases(),
287
3.01k
                   "The maximum number of phases that DistributedLB will attempt");
288
289
  // set up init value for LBPeriod time in seconds
290
  // it can also be set by calling LBSetPeriod/LBManager::SetLBPeriod
291
3.01k
  CmiGetArgDoubleDesc(argv, "+LBPeriod", &_lb_args.lbperiod(),
292
3.01k
                      "the minimum time period in seconds allowed for two consecutive "
293
3.01k
                      "automatic load balancing");
294
3.01k
  _lb_args.loop() = CmiGetArgFlagDesc(argv, "+LBLoop",
295
3.01k
                                      "Use multiple load balancing strategies in loop");
296
297
  // now called in cldb.C: CldModuleGeneralInit()
298
  // registerLBTopos();
299
3.01k
  CmiGetArgStringDesc(argv, "+LBTopo", &_lbtopo, "define load balancing topology");
300
301
  /**************** FUTURE PREDICTOR ****************/
302
3.01k
  _lb_predict = CmiGetArgFlagDesc(argv, "+LBPredictor", "Turn on LB future predictor");
303
3.01k
  CmiGetArgIntDesc(argv, "+LBPredictorDelay", &_lb_predict_delay,
304
3.01k
                   "Number of balance steps before learning a model");
305
3.01k
  CmiGetArgIntDesc(argv, "+LBPredictorWindow", &_lb_predict_window,
306
3.01k
                   "Number of steps to use to learn a model");
307
3.01k
  if (_lb_predict_window < _lb_predict_delay)
308
0
  {
309
0
    CmiPrintf(
310
0
        "LB> [%d] Argument LBPredictorWindow (%d) less than LBPredictorDelay (%d) , "
311
0
        "fixing\n",
312
0
        CkMyPe(), _lb_predict_window, _lb_predict_delay);
313
0
    _lb_predict_delay = _lb_predict_window;
314
0
  }
315
316
  /******************* SIMULATION *******************/
317
  // get the step number at which to dump the LB database
318
3.01k
  CmiGetArgIntDesc(argv, "+LBVersion", &_lb_args.lbversion(),
319
3.01k
                   "LB database file version number");
320
3.01k
  CmiGetArgIntDesc(argv, "+LBCentPE", &_lb_args.central_pe(), "CentralLB processor");
321
3.01k
  CmiGetArgIntDesc(argv, "+LBPercentMovesAllowed", &_lb_args.percentMovesAllowed(),
322
3.01k
                   "For the greedy-refine balancers, the percentage of chares that can be moved");
323
3.01k
  CmiGetArgDoubleDesc(argv, "+LBGreedyRefineTolerance", &_lb_args.greedyRefineTolerance(),
324
3.01k
                      "For the greedy-refine balancers, how far above plain greedy's max load to "
325
3.01k
                      "allow in exchange for fewer migrations (1.1 = 10% higher, the default). 0 or below runs the parameter search instead");
326
3.01k
  bool _lb_dump_activated = false;
327
3.01k
  if (CmiGetArgIntDesc(argv, "+LBDump", &LBSimulation::dumpStep,
328
3.01k
                       "Dump the LB state from this step"))
329
5
    _lb_dump_activated = true;
330
3.01k
  if (_lb_dump_activated && LBSimulation::dumpStep < 0)
331
0
  {
332
0
    CmiPrintf("LB> Argument LBDump (%d) negative, setting to 0\n",
333
0
              LBSimulation::dumpStep);
334
0
    LBSimulation::dumpStep = 0;
335
0
  }
336
3.01k
  CmiGetArgIntDesc(argv, "+LBDumpSteps", &LBSimulation::dumpStepSize,
337
3.01k
                   "Dump the LB state for this amount of steps");
338
3.01k
  if (LBSimulation::dumpStepSize <= 0)
339
0
  {
340
0
    CmiPrintf("LB> Argument LBDumpSteps (%d) too small, setting to 1\n",
341
0
              LBSimulation::dumpStepSize);
342
0
    LBSimulation::dumpStepSize = 1;
343
0
  }
344
3.01k
  CmiGetArgStringDesc(argv, "+LBDumpFile", &LBSimulation::dumpFile,
345
3.01k
                      "Set the LB state file name");
346
  // get the simulation flag and number. Now the flag can also be avoided by the presence
347
  // of the number
348
3.01k
  LBSimulation::doSimulation =
349
3.01k
      CmiGetArgIntDesc(argv, "+LBSim", &LBSimulation::simStep,
350
3.01k
                       "Read LB state from LBDumpFile since this step");
351
  // check for stupid LBSim parameter
352
3.01k
  if (LBSimulation::doSimulation && LBSimulation::simStep < 0)
353
0
  {
354
0
    CkAbort("LB> Argument LBSim (%d) invalid, should be >= 0\n", LBSimulation::simStep);
355
0
    return;
356
0
  }
357
3.01k
  CmiGetArgIntDesc(argv, "+LBSimSteps", &LBSimulation::simStepSize,
358
3.01k
                   "Read LB state for this number of steps");
359
3.01k
  if (LBSimulation::simStepSize <= 0)
360
0
  {
361
0
    CmiPrintf("LB> Argument LBSimSteps (%d) too small, setting to 1\n",
362
0
              LBSimulation::simStepSize);
363
0
    LBSimulation::simStepSize = 1;
364
0
  }
365
366
3.01k
  LBSimulation::simProcs = 0;
367
3.01k
  CmiGetArgIntDesc(argv, "+LBSimProcs", &LBSimulation::simProcs,
368
3.01k
                   "Number of target processors.");
369
370
3.01k
  LBSimulation::showDecisionsOnly =
371
3.01k
      CmiGetArgFlagDesc(argv, "+LBShowDecisions",
372
3.01k
                        "Write to File: Load Balancing Object to Processor Map decisions "
373
3.01k
                        "during LB Simulation");
374
375
  // force a global barrier after migration done
376
3.01k
  _lb_args.syncResume() = CmiGetArgFlagDesc(
377
3.01k
      argv, "+LBSyncResume", "LB performs a barrier after migration is finished");
378
379
  // both +LBDebug and +LBDebug level should work
380
3.01k
  if (!CmiGetArgIntDesc(argv, "+LBDebug", &_lb_args.debug(),
381
3.01k
                        "Turn on LB debugging printouts"))
382
2.99k
    _lb_args.debug() =
383
2.99k
        CmiGetArgFlagDesc(argv, "+LBDebug", "Turn on LB debugging printouts");
384
385
  // ask to print summary/quality of load balancer
386
3.01k
  _lb_args.printSummary() =
387
3.01k
      CmiGetArgFlagDesc(argv, "+LBPrintSummary", "Print load balancing result summary");
388
389
  // to ignore baclground load
390
3.01k
  _lb_args.ignoreBgLoad() = CmiGetArgFlagDesc(
391
3.01k
      argv, "+LBNoBackground", "Load balancer ignores the background load.");
392
3.01k
  _lb_args.migObjOnly() = CmiGetArgFlagDesc(
393
3.01k
      argv, "+LBObjOnly", "Only load balancing migratable objects, ignoring all others.");
394
3.01k
  if (_lb_args.migObjOnly()) _lb_args.ignoreBgLoad() = true;
395
396
  // assume all CPUs are identical
397
3.01k
  _lb_args.testPeSpeed() =
398
3.01k
      CmiGetArgFlagDesc(argv, "+LBTestPESpeed", "Load balancer test all CPUs speed.");
399
3.01k
  _lb_args.samePeSpeed() = CmiGetArgFlagDesc(
400
3.01k
      argv, "+LBSameCpus", "Load balancer assumes all CPUs are of same speed.");
401
3.01k
  if (!_lb_args.testPeSpeed()) _lb_args.samePeSpeed() = true;
402
403
3.01k
  _lb_args.useCpuTime() = CmiGetArgFlagDesc(
404
3.01k
      argv, "+LBUseCpuTime", "Load balancer uses CPU time instead of wallclock time.");
405
406
  // turn instrumentation off at startup
407
3.01k
  _lb_args.statsOn() =
408
3.01k
      !CmiGetArgFlagDesc(argv, "+LBOff", "Turn load balancer instrumentation off");
409
410
  // turn instrumentation of communication on at startup
411
3.01k
  _lb_args.traceComm() = CmiGetArgFlagDesc(
412
3.01k
    argv, "+LBCommOn", "Turn load balancer instrumentation of communication on");
413
414
  // +LBCommOff is deprecated as instrumentation of communication is off by default
415
3.01k
  bool lbcommOff = CmiGetArgFlagDesc(
416
3.01k
      argv, "+LBCommOff", "(No-op) Turn load balancer instrumentation of communication off");
417
3.01k
  if(CkMyPe()==0 && lbcommOff)
418
0
    CmiPrintf("Warning: Ignoring the deprecated +LBCommOff option as communication is off by default.\n");
419
420
  // set alpha and beta
421
3.01k
  _lb_args.alpha() = PER_MESSAGE_SEND_OVERHEAD_DEFAULT;
422
3.01k
  _lb_args.beta() = PER_BYTE_SEND_OVERHEAD_DEFAULT;
423
3.01k
  CmiGetArgDoubleDesc(argv, "+LBAlpha", &_lb_args.alpha(), "per message send overhead");
424
3.01k
  CmiGetArgDoubleDesc(argv, "+LBBeta", &_lb_args.beta(), "per byte send overhead");
425
426
3.01k
  if (CkMyPe() == 0)
427
952
  {
428
952
    if (_lb_args.debug())
429
36
    {
430
36
      CmiPrintf("CharmLB> Verbose level %d, load balancing period: %g seconds\n",
431
36
                _lb_args.debug(), _lb_args.lbperiod());
432
36
    }
433
952
    if (_lb_args.debug() > 1)
434
4
    {
435
4
      CmiPrintf("CharmLB> Topology %s alpha: %es beta: %es.\n", _lbtopo, _lb_args.alpha(),
436
4
                _lb_args.beta());
437
4
    }
438
952
    if (_lb_args.printSummary())
439
4
      CmiPrintf("CharmLB> Load balancer print summary of load balancing result.\n");
440
952
    if (_lb_args.ignoreBgLoad())
441
8
      CmiPrintf("CharmLB> Load balancer ignores processor background load.\n");
442
952
    if (_lb_args.samePeSpeed())
443
951
      CmiPrintf("CharmLB> Load balancer assumes all CPUs are same.\n");
444
952
    if (_lb_args.useCpuTime())
445
0
      CmiPrintf("CharmLB> Load balancer uses CPU time instead of wallclock time.\n");
446
952
    if (LBSimulation::doSimulation)
447
2
      CmiPrintf(
448
2
          "CharmLB> Load balancer running in simulation mode on file '%s' version %d.\n",
449
2
          LBSimulation::dumpFile, _lb_args.lbversion());
450
952
    if (_lb_args.statsOn() == 0)
451
0
      CkPrintf("CharmLB> Load balancing instrumentation is off.\n");
452
952
    if (_lb_args.migObjOnly())
453
8
      CkPrintf("LB> Load balancing strategy ignores non-migratable objects.\n");
454
952
  }
455
3.01k
}
456
457
bool LBManager::manualOn = false;
458
std::vector<char> LBManager::avail_vector;
459
bool LBManager::avail_vector_set = false;
460
CmiNodeLock avail_vector_lock;
461
462
static LBRealType* _expectedLoad = NULL;
463
464
void LBManager::initnodeFn()
465
1.37k
{
466
1.37k
  int proc;
467
1.37k
  int num_proc = CkNumPes();
468
1.37k
  avail_vector.clear();
469
1.37k
  avail_vector.resize(num_proc, 1);
470
1.37k
  avail_vector_lock = CmiCreateLock();
471
472
1.37k
  _expectedLoad = new LBRealType[num_proc];
473
6.36k
  for (proc = 0; proc < num_proc; proc++) _expectedLoad[proc] = 0.0;
474
475
1.37k
  _registerCommandLineOpt("+balancer");
476
1.37k
  _registerCommandLineOpt("+LBPeriod");
477
1.37k
  _registerCommandLineOpt("+TreeLBFile");
478
1.37k
  _registerCommandLineOpt("+LBLoop");
479
1.37k
  _registerCommandLineOpt("+LBTopo");
480
1.37k
  _registerCommandLineOpt("+LBPredictor");
481
1.37k
  _registerCommandLineOpt("+LBPredictorDelay");
482
1.37k
  _registerCommandLineOpt("+LBPredictorWindow");
483
1.37k
  _registerCommandLineOpt("+LBVersion");
484
1.37k
  _registerCommandLineOpt("+LBCentPE");
485
1.37k
  _registerCommandLineOpt("+LBPercentMovesAllowed");
486
1.37k
  _registerCommandLineOpt("+LBDump");
487
1.37k
  _registerCommandLineOpt("+LBDumpSteps");
488
1.37k
  _registerCommandLineOpt("+LBDumpFile");
489
1.37k
  _registerCommandLineOpt("+LBSim");
490
1.37k
  _registerCommandLineOpt("+LBSimSteps");
491
1.37k
  _registerCommandLineOpt("+LBSimProcs");
492
1.37k
  _registerCommandLineOpt("+LBShowDecisions");
493
1.37k
  _registerCommandLineOpt("+LBSyncResume");
494
1.37k
  _registerCommandLineOpt("+LBDebug");
495
1.37k
  _registerCommandLineOpt("+LBPrintSummary");
496
1.37k
  _registerCommandLineOpt("+LBNoBackground");
497
1.37k
  _registerCommandLineOpt("+LBObjOnly");
498
1.37k
  _registerCommandLineOpt("+LBTestPESpeed");
499
1.37k
  _registerCommandLineOpt("+LBSameCpus");
500
1.37k
  _registerCommandLineOpt("+LBUseCpuTime");
501
1.37k
  _registerCommandLineOpt("+LBOff");
502
1.37k
  _registerCommandLineOpt("+LBCommOn");
503
1.37k
  _registerCommandLineOpt("+LBCommOff");
504
1.37k
  _registerCommandLineOpt("+MetaLB");
505
1.37k
  _registerCommandLineOpt("+LBAlpha");
506
1.37k
  _registerCommandLineOpt("+LBBeta");
507
1.37k
}
508
509
void LBManager::InvokeLB()
510
7.02k
{
511
7.02k
  if (loadbalancers.size() > 0)
512
6.85k
  {
513
6.85k
    loadbalancers[currentLBIndex]->InvokeLB();
514
6.85k
  }
515
162
  else
516
162
  {
517
162
    ResumeClients();
518
162
  }
519
7.02k
}
520
521
// Called at end of each load balancing cycle
522
void LBManager::periodicLB(void* in)
523
6
{
524
6
  auto* const manager = static_cast<LBManager*>(in);
525
6
  manager->isPeriodicQueued = false;
526
6
  manager->InvokeLB();
527
6
}
528
529
void LBManager::setTimer()
530
12
{
531
12
  if (!isPeriodicQueued)
532
12
  {
533
12
    isPeriodicQueued = true;
534
12
    CcdCallFnAfterOnPE((CcdVoidFn)periodicLB, (void*)this, 1000 * _lb_args.lbperiod(),
535
12
                       CkMyPe());
536
12
  }
537
12
}
538
539
// called my constructor
540
void LBManager::init(void)
541
3.26k
{
542
3.26k
  mystep = 0;
543
3.26k
  new_ld_balancer = 0;
544
3.26k
  chare_count = 0;
545
3.26k
  metabalancer = nullptr;
546
3.26k
  lbdb_obj = new LBDatabase();
547
3.26k
  currentLBIndex = 0;
548
#if CMK_LB_CPUTIMER
549
  obj_cputime = 0;
550
#endif
551
3.26k
  useBarrier = true;
552
3.26k
  predictCBFn = nullptr;
553
3.26k
  startLBFn_count = 0;
554
555
3.26k
  CkpvAccess(lbmanagerInited) = true;
556
3.26k
#if CMK_LBDB_ON
557
3.26k
  if (manualOn) TurnManualLBOn();
558
3.26k
#endif
559
3.26k
  objLoadsCollecting = false;
560
  // Registered through the C-level table, which exists since ConverseInit:
561
  // the CkCallback form broadcasts to the callback group, which is not
562
  // created yet when this group is constructed.
563
3.26k
  if (CkMyPe() == 0) CcsRegisterHandler("LBObjLoads", (CmiHandler)LBObjLoadsCcsHandler);
564
565
3.26k
  if (CkMyPe()==0 && _lb_args.traceComm() == 0 && !quietModeRequested)
566
571
      CkPrintf("CharmLB> Load balancing instrumentation for communication is off.\n");
567
568
3.26k
  if (_lb_args.lbperiod() > 0.0)
569
6
  {
570
6
    setTimer();
571
6
  }
572
3.26k
  else
573
3.26k
  {
574
7.04k
    CkSyncBarrier::object()->addReceiver([this](void) { this->InvokeLB(); });
575
3.26k
  }
576
3.26k
}
577
578
/* CCS handler "LBObjLoads": a snapshot of the load database on every PE.
579
580
   Reply, in the job's native byte order: int32 numPes, then one record per
581
   PE in reduction order (the pe field says which):
582
     int32 pe, double wallNow, double totalWall, double idleWall, int32 nObjs,
583
     nObjs x { uint64 objId, int32 omGroupIdx, double objWall, uint8 migratable }
584
   The times are the database's cumulative values since the last ClearLoads
585
   (a load-balancing step); a client takes differences between snapshots. */
586
/* Converse-level CCS handler on PE 0: take the reply token and hand the
587
   request to the local LBManager branch. */
588
void LBObjLoadsCcsHandler(char* msg)
589
2
{
590
2
  CcsDelayedReply token = CcsDelayReply();
591
2
  CmiFree(msg);
592
2
  LBManager::Object()->objLoadsRequest(token);
593
2
}
594
595
void LBManager::objLoadsRequest(const CcsDelayedReply& token)
596
2
{
597
2
  objLoadsReplies.push_back(token);
598
2
  if (!objLoadsCollecting)
599
2
  {
600
2
    objLoadsCollecting = true;
601
2
    thisProxy.collectObjLoads();
602
2
  }
603
2
}
604
605
void LBManager::collectObjLoads()
606
4
{
607
  // Reports what the database holds and never switches the
608
  // instrumentation on or off: that is the program's decision
609
  // (LBTurnInstrumentOn/Off, +LBOff). A program linked -tracemode
610
  // utilization also answers "CkPerfObjLoads", the same layout from the
611
  // trace events, which does not depend on this switch.
612
4
  std::vector<char> buf;
613
276
  auto put = [&buf](const void* p, size_t n) {
614
276
    buf.insert(buf.end(), (const char*)p, (const char*)p + n);
615
276
  };
616
4
  int pe = CkMyPe();
617
4
  double now = CkWallTimer();
618
4
  LBRealType totalWall = 0, totalCpu = 0, idle = 0, bgWall = 0, bgCpu = 0;
619
4
  lbdb_obj->GetTime(&totalWall, &totalCpu, &idle, &bgWall, &bgCpu);
620
4
  double tw = totalWall, id = idle;
621
4
  const auto& objs = lbdb_obj->getObjs();
622
4
  int n = 0;
623
4
  for (const auto& e : objs)
624
64
    if (e.obj) n++;
625
4
  put(&pe, sizeof(int));
626
4
  put(&now, sizeof(double));
627
4
  put(&tw, sizeof(double));
628
4
  put(&id, sizeof(double));
629
4
  put(&n, sizeof(int));
630
4
  for (const auto& e : objs)
631
64
  {
632
64
    if (!e.obj) continue;
633
64
    const LDObjData& d = e.obj->ObjData();
634
64
    CmiUInt8 objId = d.objID();
635
64
    int om = d.omID().id.idx;
636
64
    double w = d.wallTime;
637
64
    unsigned char mig = d.migratable ? 1 : 0;
638
64
    put(&objId, sizeof(CmiUInt8));
639
64
    put(&om, sizeof(int));
640
64
    put(&w, sizeof(double));
641
64
    put(&mig, 1);
642
64
  }
643
4
  contribute(buf.size(), buf.data(), CkReduction::concat,
644
4
             CkCallback(CkIndex_LBManager::objLoadsCollected(NULL), thisProxy[0]));
645
4
}
646
647
void LBManager::objLoadsCollected(CkReductionMsg* m)
648
2
{
649
2
  int npes = CkNumPes();
650
2
  std::vector<char> out(sizeof(int) + m->getSize());
651
2
  memcpy(out.data(), &npes, sizeof(int));
652
2
  memcpy(out.data() + sizeof(int), m->getData(), m->getSize());
653
2
  for (const CcsDelayedReply& r : objLoadsReplies)
654
2
    CcsSendDelayedReply(r, (int)out.size(), out.data());
655
2
  objLoadsReplies.clear();
656
2
  objLoadsCollecting = false;
657
2
  delete m;
658
2
}
659
660
int LBManager::AddStartLBFn(std::function<void()> fn)
661
957
{
662
  // Save startLB function
663
957
  StartLBCB* callbk = new StartLBCB;
664
665
957
  callbk->fn = fn;
666
957
  callbk->on = true;
667
957
  startLBFnList.push_back(callbk);
668
957
  startLBFn_count++;
669
957
  return startLBFnList.size() - 1;
670
957
}
671
672
void LBManager::RemoveStartLBFn(int handle)
673
0
{
674
0
  StartLBCB* callbk = startLBFnList[handle];
675
0
  if (callbk)
676
0
  {
677
0
    delete callbk;
678
0
    startLBFnList[handle] = nullptr;
679
0
    startLBFn_count--;
680
0
  }
681
0
}
682
683
void LBManager::StartLB()
684
14
{
685
14
  if (startLBFn_count == 0)
686
0
  {
687
0
    CmiAbort("StartLB is not supported in this LB");
688
0
  }
689
28
  for (int i = 0; i < startLBFnList.size(); i++)
690
14
  {
691
14
    StartLBCB* startLBFn = startLBFnList[i];
692
14
    if (startLBFn && startLBFn->on) startLBFn->fn();
693
14
  }
694
14
}
695
696
int LBManager::AddMigrationDoneFn(std::function<void()> fn)
697
0
{
698
  // Save migrationDone callback function
699
0
  MigrationDoneCB* callbk = new MigrationDoneCB;
700
701
0
  callbk->fn = fn;
702
0
  migrationDoneCBList.push_back(callbk);
703
0
  return migrationDoneCBList.size() - 1;
704
0
}
705
706
void LBManager::RemoveMigrationDoneFn(int handle)
707
0
{
708
0
  MigrationDoneCB* callbk = migrationDoneCBList[handle];
709
0
  if (callbk)
710
0
  {
711
0
    delete callbk;
712
0
    migrationDoneCBList[handle] = nullptr;
713
0
  }
714
0
}
715
716
void LBManager::MigrationDone()
717
6.70k
{
718
6.70k
  for (int i = 0; i < migrationDoneCBList.size(); i++)
719
0
  {
720
0
    MigrationDoneCB* callbk = migrationDoneCBList[i];
721
0
    if (callbk) callbk->fn();
722
0
  }
723
6.70k
}
724
725
void LBManager::DumpDatabase()
726
0
{
727
#ifdef DEBUG
728
  CmiPrintf("Database contains %d object managers\n", omCount);
729
  CmiPrintf("Database contains %d objects\n", objs.size());
730
#endif
731
0
}
732
733
void LBManager::Migrated(LDObjHandle h, int waitBarrier)
734
76.1k
{
735
  // Object migrated, inform load balancers
736
76.1k
  if (loadbalancers.size() > 0) loadbalancers[currentLBIndex]->Migrated(waitBarrier);
737
76.1k
}
738
739
3.26k
LBManager::LastLBInfo::LastLBInfo() { expectedLoad = _expectedLoad; }
740
741
void LBManager::get_avail_vector(char* bitmap) const
742
98
{
743
98
  CmiAssert(bitmap);
744
98
  const int num_proc = CkNumPes();
745
98
  CmiAssert(num_proc <= avail_vector.size());
746
98
  std::copy(avail_vector.begin(), avail_vector.begin() + num_proc, bitmap);
747
98
}
748
749
// new_ld == -1(default) : calcualte a new ld
750
//           -2 : ignore new ld
751
//           >=0: given a new ld
752
void LBManager::set_avail_vector(const char* bitmap, int new_ld)
753
0
{
754
0
  int assigned = 0;
755
0
  const int num_proc = CkNumPes();
756
0
  if (new_ld == -2)
757
0
    assigned = 1;
758
0
  else if (new_ld >= 0)
759
0
  {
760
0
    CmiAssert(new_ld < num_proc);
761
0
    new_ld_balancer = new_ld;
762
0
    assigned = 1;
763
0
  }
764
0
  CmiAssert(bitmap);
765
0
  CmiAssert(num_proc <= avail_vector.size());
766
0
  for (int count = 0; count < num_proc; count++)
767
0
  {
768
0
    avail_vector[count] = bitmap[count];
769
0
    if ((bitmap[count] == 1) && !assigned)
770
0
    {
771
0
      new_ld_balancer = count;
772
0
      assigned = 1;
773
0
    }
774
0
  }
775
0
}
776
void LBManager::set_avail_vector(const std::vector<char> & bitmap, int new_ld)
777
118
{
778
118
  int assigned = 0;
779
118
  const int num_proc = CkNumPes();
780
118
  if (new_ld == -2)
781
0
    assigned = 1;
782
118
  else if (new_ld >= 0)
783
118
  {
784
118
    CmiAssert(new_ld < num_proc);
785
118
    new_ld_balancer = new_ld;
786
118
    assigned = 1;
787
118
  }
788
118
  avail_vector = bitmap;
789
590
  for (int count = 0; count < num_proc; count++)
790
472
  {
791
472
    if (bitmap[count] == 1 && !assigned)
792
0
    {
793
0
      new_ld_balancer = count;
794
0
      assigned = 1;
795
0
    }
796
472
  }
797
118
}
798
799
// called in CreateFooLB() when multiple load balancers are created
800
// on PE0, BaseLB of each load balancer applies a ticket number
801
// and broadcast the ticket number to all processors
802
int LBManager::getLoadbalancerTicket()
803
274
{
804
274
  loadbalancers.push_back(nullptr);
805
274
  return loadbalancers.size() - 1;
806
274
}
807
808
void LBManager::addLoadbalancer(BaseLB* lb, int seq)
809
946
{
810
  //  CmiPrintf("[%d] addLoadbalancer for seq %d\n", CkMyPe(), seq);
811
946
  if (seq == -1) return;
812
946
  if (CkMyPe() == 0)
813
274
  {
814
274
    CmiAssert(seq < loadbalancers.size());
815
274
    if (loadbalancers[seq])
816
0
    {
817
0
      CmiPrintf("Duplicate load balancer created at %d\n", seq);
818
0
      CmiAbort("LBManager");
819
0
    }
820
274
  }
821
946
  if (loadbalancers.size() < seq + 1)
822
654
    loadbalancers.resize(seq + 1);
823
946
  loadbalancers[seq] = lb;
824
946
}
825
826
// switch strategy in order
827
void LBManager::nextLoadbalancer(int seq)
828
6.69k
{
829
6.69k
  if (seq == -1) return;  // -1 means this is the only LB
830
6.69k
  currentLBIndex = seq + 1;
831
6.69k
  if (_lb_args.loop())
832
24
  {
833
24
    if (currentLBIndex == loadbalancers.size()) currentLBIndex = 0;
834
24
  }
835
6.66k
  else
836
6.66k
  {
837
6.66k
    if (currentLBIndex == loadbalancers.size()) currentLBIndex--;  // keep using the last one
838
6.66k
  }
839
6.69k
  if (seq != currentLBIndex)
840
40
  {
841
40
    loadbalancers[seq]->turnOff();
842
40
    CmiAssert(loadbalancers[currentLBIndex]);
843
40
    loadbalancers[currentLBIndex]->turnOn();
844
40
  }
845
6.69k
}
846
847
// switch strategy
848
void LBManager::switchLoadbalancer(int switchFrom, int switchTo)
849
633
{
850
633
  if (lbNames[switchTo] != "DistributedLB" && lbNames[switchTo] != "MetisLB")
851
473
  {
852
473
    json config;
853
473
    if (lbNames[switchTo] == "Hybrid")
854
399
    {
855
399
      config["tree"] = "PE_Process_Root";
856
399
      config["root"]["pe"] = 0;
857
399
      config["root"]["step_freq"] = 3;
858
399
      config["root"]["strategies"] = {"GreedyRefine"};
859
399
      config["process"]["strategies"] = {"GreedyRefine"};
860
399
    }
861
74
    else
862
74
    {
863
74
      config["tree"] = "PE_Root";
864
74
      config["root"]["pe"] = 0;
865
74
      config["root"]["strategies"] = {lbNames[switchTo]};
866
74
    }
867
473
    configureTreeLB(config);
868
473
  }
869
160
  else
870
160
  {
871
    // TODO: Implement turn off / on for Distributed
872
160
  }
873
633
}
874
875
// return the seq-th load balancer string name of
876
// it can be specified in either compile time or runtime
877
// runtime has higher priority
878
const char* LBManager::loadbalancer(int seq)
879
0
{
880
0
  if (!lbRegistry.runtime_lbs.empty())
881
0
  {
882
0
    CmiAssert(seq < lbRegistry.runtime_lbs.size());
883
0
    return lbRegistry.runtime_lbs[seq];
884
0
  }
885
0
  else
886
0
  {
887
0
    CmiAssert(seq < lbRegistry.compile_lbs.size());
888
0
    return lbRegistry.compile_lbs[seq];
889
0
  }
890
0
}
891
892
void LBManager::pup(PUP::er& p)
893
246
{
894
246
  IrrGroup::pup(p);
895
246
  if (p.isUnpacking())
896
143
  {
897
    // Since avail_vector is static, only unpack one of them for real in SMP mode, the
898
    // rest to some tmp variable
899
143
    CmiLock(avail_vector_lock);
900
143
    if (!avail_vector_set)
901
60
    {
902
60
      avail_vector_set = true;
903
60
      p | avail_vector;
904
      // If we're restarting with more PEs, make the new ones available
905
60
      if (avail_vector.size() < CkNumPes())
906
7
        avail_vector.resize(CkNumPes(), 1);
907
60
    }
908
83
    else
909
83
    {
910
83
      decltype(avail_vector) tmp;
911
83
      p | tmp;
912
83
    }
913
143
    CmiUnlock(avail_vector_lock);
914
143
  }
915
103
  else
916
103
  {
917
103
    p | avail_vector;
918
103
  }
919
246
  p | mystep;
920
246
  if (p.isUnpacking())
921
143
  {
922
143
    if (_lb_args.metaLbOn())
923
0
    {
924
      // if unpacking set metabalancer using the id
925
0
      metabalancer = (MetaBalancer*)CkLocalBranch(_metalb);
926
0
    }
927
143
  }
928
246
}
929
930
void configureTreeLB(const char* json_str)
931
0
{
932
0
  ((LBManager*)CkLocalBranch(_lbmgr))->configureTreeLB(json_str);
933
0
}
934
935
void LBManager::configureTreeLB(const char* json_str)
936
0
{
937
0
  json config = json::parse(json_str);
938
0
  configureTreeLB(config);
939
0
}
940
941
void LBManager::configureTreeLB(json& config)
942
488
{
943
488
  bool found = false;
944
957
  for (int i = 0; i < loadbalancers.size(); i++)
945
469
  {
946
469
    if (strcmp(loadbalancers[i]->lbName(), "TreeLB") == 0)
947
470
    {
948
470
      ((TreeLB*)loadbalancers[i])->configure(config);
949
470
      found = true;
950
      // break; // not sure if there could be more than one TreeLB
951
470
    }
952
469
  }
953
488
  if (!found) CkAbort("LBManager: TreeLB is not in my list of load balancers");
954
488
}
955
956
void LBManager::ResetAdaptive()
957
118
{
958
118
#if CMK_LBDB_ON
959
118
  if (_lb_args.metaLbOn())
960
0
  {
961
0
    if (metabalancer == NULL)
962
0
    {
963
0
      metabalancer = CProxy_MetaBalancer(_metalb).ckLocalBranch();
964
0
    }
965
0
    if (metabalancer != NULL)
966
0
    {
967
0
      metabalancer->ResetAdaptive();
968
0
    }
969
0
  }
970
118
#endif
971
118
}
972
973
void LBManager::ResumeClients()
974
7.07k
{
975
7.07k
#if CMK_LBDB_ON
976
7.07k
  if (_lb_args.metaLbOn())
977
177
  {
978
177
    if (metabalancer == NULL)
979
20
    {
980
20
      metabalancer = CProxy_MetaBalancer(_metalb).ckLocalBranch();
981
20
    }
982
177
    if (metabalancer != NULL)
983
177
    {
984
177
      metabalancer->ResumeClients();
985
177
    }
986
177
  }
987
988
  // If periodic is enabled, reset the timer and don't resume clients
989
7.07k
  if (_lb_args.lbperiod() != -1.0)
990
6
  {
991
6
    setTimer();
992
6
  }
993
7.06k
  else
994
7.06k
  {
995
7.06k
    CkSyncBarrier::object()->resumeClients();
996
7.06k
  }
997
7.07k
#endif
998
7.07k
}
999
1000
void LBManager::SetMigrationCost(double cost)
1001
381
{
1002
381
#if CMK_LBDB_ON
1003
381
  if (_lb_args.metaLbOn())
1004
0
  {
1005
0
    if (metabalancer == NULL)
1006
0
    {
1007
0
      metabalancer = (MetaBalancer*)CkLocalBranch(_metalb);
1008
0
    }
1009
0
    if (metabalancer != NULL)
1010
0
    {
1011
0
      metabalancer->SetMigrationCost(cost);
1012
0
    }
1013
0
  }
1014
381
#endif
1015
381
}
1016
1017
void LBManager::SetStrategyCost(double cost)
1018
100
{
1019
100
#if CMK_LBDB_ON
1020
100
  if (_lb_args.metaLbOn())
1021
0
  {
1022
0
    if (metabalancer == NULL)
1023
0
    {
1024
0
      metabalancer = (MetaBalancer*)CkLocalBranch(_metalb);
1025
0
    }
1026
0
    if (metabalancer != NULL)
1027
0
    {
1028
0
      metabalancer->SetStrategyCost(cost);
1029
0
    }
1030
0
  }
1031
100
#endif
1032
100
}
1033
1034
void LBManager::UpdateDataAfterLB(double mLoad, double mCpuLoad, double avgLoad)
1035
0
{
1036
0
#if CMK_LBDB_ON
1037
0
  if (_lb_args.metaLbOn())
1038
0
  {
1039
0
    if (metabalancer == NULL)
1040
0
    {
1041
0
      metabalancer = (MetaBalancer*)CkLocalBranch(_metalb);
1042
0
    }
1043
0
    if (metabalancer != NULL)
1044
0
    {
1045
0
      metabalancer->UpdateAfterLBData(mLoad, mCpuLoad, avgLoad);
1046
0
    }
1047
0
  }
1048
0
#endif
1049
0
}
1050
1051
LDBarrierClient LBManager::AddLocalBarrierClient(Chare* obj, std::function<void()> fn)
1052
0
{
1053
0
  return CkSyncBarrier::object()->addClient(obj, fn);
1054
0
}
1055
1056
void LBManager::RemoveLocalBarrierClient(LDBarrierClient h)
1057
0
{
1058
0
  CkSyncBarrier::object()->removeClient(h);
1059
0
}
1060
1061
LDBarrierReceiver LBManager::AddLocalBarrierReceiver(std::function<void()> fn)
1062
0
{
1063
0
  return CkSyncBarrier::object()->addReceiver(fn);
1064
0
}
1065
1066
void LBManager::RemoveLocalBarrierReceiver(LDBarrierReceiver h)
1067
0
{
1068
0
  CkSyncBarrier::object()->removeReceiver(h);
1069
0
}
1070
1071
void LBManager::AtLocalBarrier(LDBarrierClient _n_c)
1072
91.6k
{
1073
91.6k
  if (useBarrier) CkSyncBarrier::object()->atBarrier(_n_c);
1074
91.6k
}
1075
1076
void LBManager::TurnOnBarrierReceiver(LDBarrierReceiver h)
1077
0
{
1078
0
  CkSyncBarrier::object()->turnOnReceiver(h);
1079
0
}
1080
1081
void LBManager::TurnOffBarrierReceiver(LDBarrierReceiver h)
1082
0
{
1083
0
  CkSyncBarrier::object()->turnOffReceiver(h);
1084
0
}
1085
1086
0
void LBManager::LocalBarrierOn(void) { CkSyncBarrier::object()->turnOn(); }
1087
0
void LBManager::LocalBarrierOff(void) { CkSyncBarrier::object()->turnOff(); }
1088
1089
#if CMK_LBDB_ON
1090
static void work(int iter_block, volatile int* result)
1091
0
{
1092
0
  int i;
1093
0
  *result = 1;
1094
0
  for (i = 0; i < iter_block; i++)
1095
0
  {
1096
0
    double b = 0.1 + 0.1 * *result;
1097
0
    *result = (int)(sqrt(1 + cos(b * 1.57)));
1098
0
  }
1099
0
}
1100
1101
int LDProcessorSpeed()
1102
54
{
1103
54
  if (_lb_args.samePeSpeed() ||
1104
54
      CkNumPes() == 1)  // I think it is safe to assume that we can
1105
54
    return 1;           // skip this if we are only using 1 PE
1106
1107
0
  volatile int result = 0;
1108
1109
0
  int wps = 0;
1110
0
  const double elapse = 0.2;
1111
  // First, count how many iterations happen in "elapse" seconds.
1112
  // Since we are doing lots of function calls, this will be rough
1113
0
  const double end_time = CmiCpuTimer() + elapse;
1114
0
  while (CmiCpuTimer() < end_time)
1115
0
  {
1116
0
    work(1000, &result);
1117
0
    wps += 1000;
1118
0
  }
1119
1120
  // Now we have a rough idea of how many iterations happen in
1121
  // "elapse" seconds, so just perform a few cycles of correction
1122
  // by running for what should take that long. Then correct the
1123
  // number of iterations if needed.
1124
1125
0
  for (int i = 0; i < 2; i++)
1126
0
  {
1127
0
    const double start_time = CmiCpuTimer();
1128
0
    work(wps, &result);
1129
0
    const double end_time = CmiCpuTimer();
1130
0
    const double correction = elapse / (end_time - start_time);
1131
0
    wps = (int)((double)wps * correction + 0.5);
1132
0
  }
1133
1134
0
  return wps;
1135
54
}
1136
1137
#else
1138
int LDProcessorSpeed() { return 1; }
1139
#endif  // CMK_LBDB_ON
1140
1141
int LBManager::ProcessorSpeed()
1142
132
{
1143
132
  static int peSpeed = LDProcessorSpeed();
1144
132
  return peSpeed;
1145
132
}
1146
1147
/*
1148
  callable from user's code
1149
*/
1150
void TurnManualLBOn()
1151
16
{
1152
16
#if CMK_LBDB_ON
1153
16
  LBManager* myLbdb = LBManager::Object();
1154
16
  if (myLbdb)
1155
0
  {
1156
0
    myLbdb->TurnManualLBOn();
1157
0
  }
1158
16
  else
1159
16
  {
1160
16
    LBManager::manualOn = true;
1161
16
  }
1162
16
#endif
1163
16
}
1164
1165
void TurnManualLBOff()
1166
0
{
1167
0
#if CMK_LBDB_ON
1168
0
  LBManager* myLbdb = LBManager::Object();
1169
0
  if (myLbdb)
1170
0
  {
1171
0
    myLbdb->TurnManualLBOff();
1172
0
  }
1173
0
  else
1174
0
  {
1175
0
    LBManager::manualOn = false;
1176
0
  }
1177
0
#endif
1178
0
}
1179
1180
void LBTurnInstrumentOn()
1181
4
{
1182
4
#if CMK_LBDB_ON
1183
4
  if (CkpvAccess(lbmanagerInited))
1184
4
    LBManager::Object()->CollectStatsOn();
1185
0
  else
1186
0
    _lb_args.statsOn() = 1;
1187
4
#endif
1188
4
}
1189
1190
void LBTurnInstrumentOff()
1191
0
{
1192
0
#if CMK_LBDB_ON
1193
0
  if (CkpvAccess(lbmanagerInited))
1194
0
    LBManager::Object()->CollectStatsOff();
1195
0
  else
1196
0
    _lb_args.statsOn() = 0;
1197
0
#endif
1198
0
}
1199
1200
void LBTurnCommOn()
1201
1.10k
{
1202
1.10k
#if CMK_LBDB_ON
1203
1.10k
  _lb_args.traceComm() = 1;
1204
1.10k
#endif
1205
1.10k
}
1206
1207
void LBTurnCommOff()
1208
0
{
1209
0
#if CMK_LBDB_ON
1210
0
  _lb_args.traceComm() = 0;
1211
0
#endif
1212
0
}
1213
1214
void LBClearLoads()
1215
0
{
1216
0
#if CMK_LBDB_ON
1217
0
  LBManager::Object()->ClearLoads();
1218
0
#endif
1219
0
}
1220
1221
void LBTurnPredictorOn(LBPredictorFunction* model)
1222
0
{
1223
0
#if CMK_LBDB_ON
1224
0
  LBManager::Object()->PredictorOn(model);
1225
0
#endif
1226
0
}
1227
1228
void LBTurnPredictorOn(LBPredictorFunction* model, int wind)
1229
0
{
1230
0
#if CMK_LBDB_ON
1231
0
  LBManager::Object()->PredictorOn(model, wind);
1232
0
#endif
1233
0
}
1234
1235
void LBTurnPredictorOff()
1236
0
{
1237
0
#if CMK_LBDB_ON
1238
0
  LBManager::Object()->PredictorOff();
1239
0
#endif
1240
0
}
1241
1242
void LBChangePredictor(LBPredictorFunction* model)
1243
0
{
1244
0
#if CMK_LBDB_ON
1245
0
  LBManager::Object()->ChangePredictor(model);
1246
0
#endif
1247
0
}
1248
1249
void LBSetPeriod(double period)
1250
0
{
1251
0
#if CMK_LBDB_ON
1252
0
  LBManager::SetLBPeriod(period);
1253
0
#endif
1254
0
}
1255
1256
0
int LBRegisterObjUserData(int size) { return CkpvAccess(lbobjdatalayout).claim(size); }
1257
1258
#include "LBManager.def.h"
1259
1260
/*@}*/