Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

40
LINES

< > BotCompany Repo | #1004539 // limitCPU - limit CPU per thread

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (3995L/23K).

sclass limitCPU_Data {
  int granularity = 10;
  double percentage;
  volatile long calcingSince;
  volatile long sleepTime, calcTime;
}

//static new ThreadLocal<limitCPU_Data> limitCPU_data;
static Map<Thread, limitCPU_Data> limitCPU_data = synchroMap(new WeakHashMap);

svoid limitCPU(double percentage) {
  if (percentage >= 100 || percentage < 0) ret;
  limitCPU_Data data = limitCPU_data.get(currentThread());
  if (data == null)
    limitCPU_data.put(currentThread(), data = new limitCPU_Data);
  if (ping_impl(false))
    data.calcingSince = 0; // ping slept, reset timer
  //limitCPU_Data data = limitCPU_data.get();
  if (data.percentage != percentage) {
    data.percentage = percentage;
    data.calcTime = data.sleepTime = 0;
  }
  if (data.calcingSince == 0) {
    data.calcingSince = now();
    ret;
  }
  long newCalcTime = now() - data.calcingSince;
  if (newCalcTime >= data.granularity) { // don't try to sleep too often
    data.calcTime += newCalcTime;
    double ratio = percentage/100;
    // todo: calc shouldSleepTime
    double allowedCalcTime = data.sleepTime*ratio/(1-ratio);
    long sleep = toLong(max(0, data.calcTime-allowedCalcTime));
    if (sleep > 0) {
      sleep(sleep);
      data.sleepTime += sleep;
    }
    data.calcingSince = now();
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, ddnzoavkxhuk, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

1 comment(s) hidden. show

Snippet ID: #1004539
Snippet name: limitCPU - limit CPU per thread
Eternal ID of this version: #1004539/7
Text MD5: f8d08079ab299127a0762e8635bf59f0
Transpilation MD5: aff508e7b454c881c35a16d9adae3d02
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2021-10-23 00:50:30
Source code size: 1321 bytes / 40 lines
Pitched / IR pitched: No / No
Views / Downloads: 943 / 919
Version history: 6 change(s)
Referenced in: [show references]