Home | History | Annotate | Download | only in simpleperfexamplepurejava
      1 package com.example.simpleperf.simpleperfexamplepurejava;
      2 
      3 import android.support.v7.app.AppCompatActivity;
      4 import android.os.Bundle;
      5 
      6 public class SleepActivity extends AppCompatActivity {
      7 
      8     @Override
      9     protected void onCreate(Bundle savedInstanceState) {
     10         super.onCreate(savedInstanceState);
     11         setContentView(R.layout.activity_sleep);
     12         createRunSleepThread();
     13     }
     14 
     15     void createRunSleepThread() {
     16         new Thread(new Runnable() {
     17             volatile int counter = 0;
     18             long totalRunTimeInNs = 0;
     19             long totalSleepTimeInNs = 0;
     20 
     21             private long RunFunction() {
     22                 long startTimeInNs = System.nanoTime();
     23                 for (int i = 0; i < 10000000; ++i) {
     24                     counter = callFunction(counter);
     25                 }
     26                 return System.nanoTime() - startTimeInNs;
     27             }
     28 
     29             private long SleepFunction(long sleepTimeInNs) {
     30                 long startTimeInNs = System.nanoTime();
     31                 try {
     32                     Thread.sleep(sleepTimeInNs / 1000000, (int) (sleepTimeInNs % 1000000));
     33                 } catch (Exception e) {
     34                 }
     35                 return System.nanoTime() - startTimeInNs;
     36             }
     37 
     38             @Override
     39             public void run() {
     40                 while (true) {
     41                     totalRunTimeInNs += RunFunction();
     42                     if (totalSleepTimeInNs < totalRunTimeInNs) {
     43                         totalSleepTimeInNs += SleepFunction(
     44                                 totalRunTimeInNs - totalSleepTimeInNs);
     45                     }
     46                 }
     47             }
     48 
     49             private int callFunction(int a) {
     50                 return a+1;
     51             }
     52         }, "RunSleepThread").start();
     53     }
     54 
     55 }
     56