Libraryless. Click here for Pure Java version (3995L/23K).
1 | sclass limitCPU_Data { |
2 | int granularity = 10; |
3 | double percentage; |
4 | volatile long calcingSince; |
5 | volatile long sleepTime, calcTime; |
6 | } |
7 | |
8 | //static new ThreadLocal<limitCPU_Data> limitCPU_data; |
9 | static Map<Thread, limitCPU_Data> limitCPU_data = synchroMap(new WeakHashMap); |
10 | |
11 | svoid limitCPU(double percentage) { |
12 | if (percentage >= 100 || percentage < 0) ret; |
13 | limitCPU_Data data = limitCPU_data.get(currentThread()); |
14 | if (data == null) |
15 | limitCPU_data.put(currentThread(), data = new limitCPU_Data); |
16 | if (ping_impl(false)) |
17 | data.calcingSince = 0; // ping slept, reset timer |
18 | //limitCPU_Data data = limitCPU_data.get(); |
19 | if (data.percentage != percentage) { |
20 | data.percentage = percentage; |
21 | data.calcTime = data.sleepTime = 0; |
22 | } |
23 | if (data.calcingSince == 0) { |
24 | data.calcingSince = now(); |
25 | ret; |
26 | } |
27 | long newCalcTime = now() - data.calcingSince; |
28 | if (newCalcTime >= data.granularity) { // don't try to sleep too often |
29 | data.calcTime += newCalcTime; |
30 | double ratio = percentage/100; |
31 | // todo: calc shouldSleepTime |
32 | double allowedCalcTime = data.sleepTime*ratio/(1-ratio); |
33 | long sleep = toLong(max(0, data.calcTime-allowedCalcTime)); |
34 | if (sleep > 0) { |
35 | sleep(sleep); |
36 | data.sleepTime += sleep; |
37 | } |
38 | data.calcingSince = now(); |
39 | } |
40 | } |
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
ID | Author/Program | Comment | Date |
---|---|---|---|
1290 | stefan | Article: https://medium.com/@stefanreich/javax-limiting-cpu-per-thread-d66c45e7b031#.2xs6rlfnz | 2016-08-20 15:14:41 |
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: | 944 / 920 |
Version history: | 6 change(s) |
Referenced in: | [show references] |