1 /* 2 * Copyright (C) 2019 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package android.gameperformance; 17 18 /** 19 * Ballast thread that emulates CPU load by performing heavy computation in loop. 20 */ 21 public class CPULoadThread extends Thread { 22 private boolean mStopRequest; 23 CPULoadThread()24 public CPULoadThread() { 25 mStopRequest = false; 26 } 27 computePi()28 private static double computePi() { 29 double accumulator = 0; 30 double prevAccumulator = -1; 31 int index = 1; 32 while (true) { 33 accumulator += ((1.0 / (2.0 * index - 1)) - (1.0 / (2.0 * index + 1))); 34 if (accumulator == prevAccumulator) { 35 break; 36 } 37 prevAccumulator = accumulator; 38 index += 2; 39 } 40 return 4 * accumulator; 41 } 42 43 // Requests thread to stop. issueStopRequest()44 public void issueStopRequest() { 45 synchronized (this) { 46 mStopRequest = true; 47 } 48 } 49 50 @Override run()51 public void run() { 52 // Load CPU by PI computation. 53 while (computePi() != 0) { 54 synchronized (this) { 55 if (mStopRequest) { 56 break; 57 } 58 } 59 } 60 } 61 } 62