summaryrefslogtreecommitdiffstats
path: root/tests/FrameworkPerf/src/com/android/frameworkperf/FrameworkPerfActivity.java
blob: 9f05a55484e7252cea480a5863f5015b5c7fce7e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.frameworkperf;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.PowerManager;
import android.os.Process;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * So you thought sync used up your battery life.
 */
public class FrameworkPerfActivity extends Activity {
    final Handler mHandler = new Handler();

    TextView mLog;
    PowerManager.WakeLock mPartialWakeLock;

    long mMaxRunTime = 5000;
    boolean mStarted;

    final TestRunner mRunner = new TestRunner();

    final Op[] mOpPairs = new Op[] {
            new MethodCallOp(), new NoOp(),
            new MethodCallOp(), new CpuOp(),
            new MethodCallOp(), new SchedulerOp(),
            new MethodCallOp(), new GcOp(),
            new SchedulerOp(), new SchedulerOp(),
            new GcOp(), new NoOp(),
            new IpcOp(), new NoOp(),
            new IpcOp(), new CpuOp(),
            new IpcOp(), new SchedulerOp(),
            new IpcOp(), new GcOp(),
            new ParseXmlResOp(), new NoOp(),
            new ParseLargeXmlResOp(), new NoOp(),
            new LayoutInflaterOp(), new NoOp(),
            new LayoutInflaterLargeOp(), new NoOp(),
            new LoadSmallBitmapOp(), new NoOp(),
            new LoadLargeBitmapOp(), new NoOp(),
            new LoadSmallScaledBitmapOp(), new NoOp(),
            new LoadLargeScaledBitmapOp(), new NoOp(),
    };

    final Op[] mAvailOps = new Op[] {
            new NoOp(),
            new CpuOp(),
            new SchedulerOp(),
            new MethodCallOp(),
            new IpcOp(),
            new ParseXmlResOp(),
            new ParseLargeXmlResOp(),
            new LoadSmallBitmapOp(),
            new LoadLargeBitmapOp(),
            new LoadSmallScaledBitmapOp(),
            new LoadLargeScaledBitmapOp(),
    };
    
    int mCurOpIndex = 0;

    class RunResult {
        final String name;
        final String fgLongName;
        final String bgLongName;
        final long fgTime;
        final long fgOps;
        final long bgTime;
        final long bgOps;

        RunResult(TestRunner op) {
            name = op.getName();
            fgLongName = op.getForegroundLongName();
            bgLongName = op.getBackgroundLongName();
            fgTime = op.getForegroundTime();
            fgOps = op.getForegroundOps();
            bgTime = op.getBackgroundTime();
            bgOps = op.getBackgroundOps();
        }

        float getFgMsPerOp() {
            return fgOps != 0 ? (fgTime / (float)fgOps) : 0;
        }

        float getBgMsPerOp() {
            return bgOps != 0 ? (bgTime / (float)bgOps) : 0;
        }
    }

    final ArrayList<RunResult> mResults = new ArrayList<RunResult>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the layout for this activity.  You can find it
        // in res/layout/hello_activity.xml
        setContentView(R.layout.main);

        findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                startRunning();
            }
        });
        findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
            @Override public void onClick(View v) {
                stopRunning();
            }
        });
        mLog = (TextView)findViewById(R.id.log);

        PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
        mPartialWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Scheduler");
        mPartialWakeLock.setReferenceCounted(false);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopRunning();
        if (mPartialWakeLock.isHeld()) {
            mPartialWakeLock.release();
        }
    }

    void startCurOp() {
        mRunner.run(mHandler, mOpPairs[mCurOpIndex], mOpPairs[mCurOpIndex+1], new Runnable() {
            @Override public void run() {
                RunResult result = new RunResult(mRunner);
                log(String.format("%s: fg=%d*%gms/op (%dms) / bg=%d*%gms/op (%dms)",
                        result.name, result.fgOps, result.getFgMsPerOp(), result.fgTime,
                        result.bgOps, result.getBgMsPerOp(), result.bgTime));
                mResults.add(result);
                if (!mStarted) {
                    log("Stop");
                    stopRunning();
                    return;
                }
                mCurOpIndex+=2;
                if (mCurOpIndex >= mOpPairs.length) {
                    log("Finished");
                    stopRunning();
                    return;
                }
                startCurOp();
            }
        });
    }

    void startRunning() {
        if (!mStarted) {
            log("Start");
            mStarted = true;
            updateWakeLock();
            startService(new Intent(this, SchedulerService.class));
            mCurOpIndex = 0;
            mResults.clear();
            startCurOp();
        }
    }

    void stopRunning() {
        if (mStarted) {
            mStarted = false;
            updateWakeLock();
            stopService(new Intent(this, SchedulerService.class));
            for (int i=0; i<mResults.size(); i++) {
                RunResult result = mResults.get(i);
                float fgMsPerOp = result.getFgMsPerOp();
                float bgMsPerOp = result.getBgMsPerOp();
                String fgMsPerOpStr = fgMsPerOp != 0 ? Float.toString(fgMsPerOp) : "";
                String bgMsPerOpStr = bgMsPerOp != 0 ? Float.toString(bgMsPerOp) : "";
                Log.i("Perf", "\t" + result.name + "\t" + result.fgOps
                        + "\t" + result.getFgMsPerOp() + "\t" + result.fgTime
                        + "\t" + result.fgLongName + "\t" + result.bgOps
                        + "\t" + result.getBgMsPerOp() + "\t" + result.bgTime
                        + "\t" + result.bgLongName);
            }
        }
    }

    void updateWakeLock() {
        if (mStarted) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            if (!mPartialWakeLock.isHeld()) {
                mPartialWakeLock.acquire();
            }
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            if (mPartialWakeLock.isHeld()) {
                mPartialWakeLock.release();
            }
        }
    }

    void log(String s) {
        mLog.setText(mLog.getText() + "\n" + s);
        Log.i("Perf", s);
    }

    enum BackgroundMode {
        NOTHING,
        CPU,
        SCHEDULER
    };

    public class TestRunner {
        Handler mHandler;
        Op mForegroundOp;
        Op mBackgroundOp;
        Runnable mDoneCallback;

        RunnerThread mBackgroundThread;
        RunnerThread mForegroundThread;
        long mStartTime;

        boolean mBackgroundRunning;
        boolean mForegroundRunning;

        long mBackgroundEndTime;
        long mBackgroundOps;
        long mForegroundEndTime;
        long mForegroundOps;

        public TestRunner() {
        }

        public String getForegroundName() {
            return mForegroundOp.getName();
        }

        public String getBackgroundName() {
            return mBackgroundOp.getName();
        }

        public String getName() {
            String fgName = mForegroundOp.getName();
            String bgName = mBackgroundOp.getName();
            StringBuilder res = new StringBuilder();
            if (fgName != null) {
                res.append(fgName);
                res.append("Fg");
            }
            if (bgName != null) {
                res.append(bgName);
                res.append("Bg");
            }
            return res.toString();
        }

        public String getForegroundLongName() {
            return mForegroundOp.getLongName();
        }

        public String getBackgroundLongName() {
            return mBackgroundOp.getLongName();
        }

        public void run(Handler handler, Op foreground, Op background, Runnable doneCallback) {
            mHandler = handler;
            mForegroundOp = foreground;
            mBackgroundOp = background;
            mDoneCallback = doneCallback;
            mBackgroundThread = new RunnerThread("background", new Runnable() {
                @Override public void run() {
                    boolean running;
                    int ops = 0;
                    do {
                        running = mBackgroundOp.onRun();
                        ops++;
                    } while (evalRepeat(running, true) && running);
                    mBackgroundEndTime = SystemClock.uptimeMillis();
                    mBackgroundOps = ops * mBackgroundOp.getOpsPerRun();
                    threadFinished(false);
                }
            }, Process.THREAD_PRIORITY_BACKGROUND);
            mForegroundThread = new RunnerThread("background", new Runnable() {
                @Override public void run() {
                    boolean running;
                    int ops = 0;
                    do {
                        running = mForegroundOp.onRun();
                        ops++;
                    } while (evalRepeat(true, running) && running);
                    mForegroundEndTime = SystemClock.uptimeMillis();
                    mForegroundOps = ops * mForegroundOp.getOpsPerRun();
                    threadFinished(true);
                }
            }, Process.THREAD_PRIORITY_FOREGROUND);

            mForegroundOp.onInit(FrameworkPerfActivity.this);
            mBackgroundOp.onInit(FrameworkPerfActivity.this);

            synchronized (this) {
                mStartTime = SystemClock.uptimeMillis();
                mBackgroundRunning = true;
                mForegroundRunning = true;
            }

            mBackgroundThread.start();
            mForegroundThread.start();
        }

        public long getForegroundTime() {
            return mForegroundEndTime-mStartTime;
        }

        public long getForegroundOps() {
            return mForegroundOps;
        }

        public long getBackgroundTime() {
            return mBackgroundEndTime-mStartTime;
        }

        public long getBackgroundOps() {
            return mBackgroundOps;
        }

        private boolean evalRepeat(boolean bgRunning, boolean fgRunning) {
            synchronized (this) {
                if (!bgRunning) {
                    mBackgroundRunning = false;
                }
                if (!fgRunning) {
                    mForegroundRunning = false;
                }
                if (!mBackgroundRunning && !mForegroundRunning) {
                    return false;
                }
                long now = SystemClock.uptimeMillis();
                if (now > (mStartTime+mMaxRunTime)) {
                    return false;
                }
                return true;
            }
        }

        private void threadFinished(boolean foreground) {
            synchronized (this) {
                if (foreground) {
                    mForegroundRunning = false;
                } else {
                    mBackgroundRunning = false;
                }
                if (!mBackgroundRunning && !mForegroundRunning) {
                    mHandler.post(new Runnable() {
                        @Override public void run() {
                            if (mDoneCallback != null) {
                                mDoneCallback.run();
                            }
                        }
                    });
                }
            }
        }
    }

    class RunnerThread extends Thread {
        private final Runnable mOp;
        private final int mPriority;

        RunnerThread(String name, Runnable op, int priority) {
            super(name);
            mOp = op;
            mPriority = priority;
        }

        public void run() {
            Process.setThreadPriority(mPriority);
            mOp.run();
        }
    }

    static public abstract class Op {
        final String mName;
        final String mLongName;

        public Op(String name, String longName) {
            mName = name;
            mLongName = longName;
        }

        public String getName() {
            return mName;
        }

        public String getLongName() {
            return mLongName;
        }

        void onInit(Context context) {
        }

        abstract boolean onRun();

        int getOpsPerRun() {
            return 1;
        }
    }

    static class NoOp extends Op {
        NoOp() {
            super(null, "Nothing");
        }

        boolean onRun() {
            return false;
        }

        int getOpsPerRun() {
            return 0;
        }
    }

    static class CpuOp extends Op {
        CpuOp() {
            super("CPU", "Consume CPU");
        }

        boolean onRun() {
            return true;
        }
    }

    static class SchedulerOp extends Op {
        SchedulerOp() {
            super("Sched", "Change scheduler group");
        }

        boolean onRun() {
            Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
            return true;
        }
    }

    static class GcOp extends Op {
        GcOp() {
            super("Gc", "Run garbage collector");
        }

        boolean onRun() {
            byte[] stuff = new byte[1024*1024];
            return true;
        }
    }

    static class MethodCallOp extends Op {
        MethodCallOp() {
            super("MethodCall", "Method call");
        }

        boolean onRun() {
            final int N = getOpsPerRun();
            for (int i=0; i<N; i++) {
                someFunc(i);
            }
            return true;
        }

        int someFunc(int foo) {
            return 0;
        }

        int getOpsPerRun() {
            return 500;
        }
    }

    static class IpcOp extends Op {
        PackageManager mPm;
        String mProcessName;

        IpcOp() {
            super("Ipc", "IPC to system process");
        }

        void onInit(Context context) {
            mPm = context.getPackageManager();
            mProcessName = context.getApplicationInfo().processName;
        }

        boolean onRun() {
            final int N = getOpsPerRun();
            for (int i=0; i<N; i++) {
                mPm.queryContentProviders(mProcessName, Process.myUid(), 0);
            }
            return true;
        }

        int getOpsPerRun() {
            return 100;
        }
    }

    static class ParseXmlResOp extends Op {
        Context mContext;

        ParseXmlResOp() {
            super("ParseXmlRes", "Parse compiled XML resource");
        }

        void onInit(Context context) {
            mContext = context;
        }

        boolean onRun() {
            SimpleInflater inf = new SimpleInflater(mContext);
            inf.inflate(R.xml.simple);
            return true;
        }
    }

    static class ParseLargeXmlResOp extends Op {
        Context mContext;

        ParseLargeXmlResOp() {
            super("ParseLargeXmlRes", "Parse large XML resource");
        }

        void onInit(Context context) {
            mContext = context;
        }

        boolean onRun() {
            SimpleInflater inf = new SimpleInflater(mContext);
            inf.inflate(R.xml.simple_large);
            return true;
        }
    }

    static class LayoutInflaterOp extends Op {
        Context mContext;

        LayoutInflaterOp() {
            super("LayoutInflaterOp", "Inflate layout resource");
        }

        void onInit(Context context) {
            mContext = context;
        }

        boolean onRun() {
            if (Looper.myLooper() == null) {
                Looper.prepare();
            }
            LayoutInflater inf = (LayoutInflater)mContext.getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            inf.inflate(R.layout.small_layout, null);
            return true;
        }
    }

    static class LayoutInflaterLargeOp extends Op {
        Context mContext;

        LayoutInflaterLargeOp() {
            super("LayoutInflaterLargeOp", "Inflate large layout resource");
        }

        void onInit(Context context) {
            mContext = context;
        }

        boolean onRun() {
            if (Looper.myLooper() == null) {
                Looper.prepare();
            }
            LayoutInflater inf = (LayoutInflater)mContext.getSystemService(
                    Context.LAYOUT_INFLATER_SERVICE);
            inf.inflate(R.layout.large_layout, null);
            return true;
        }
    }

    static class LoadSmallBitmapOp extends Op {
        Context mContext;

        LoadSmallBitmapOp() {
            super("LoadSmallBitmap", "Load small raw bitmap");
        }

        void onInit(Context context) {
            mContext = context;
        }

        boolean onRun() {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE;
            Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(),
                    R.drawable.stat_sample, opts);
            bm.recycle();
            return true;
        }
    }

    static class LoadLargeBitmapOp extends Op {
        Context mContext;

        LoadLargeBitmapOp() {
            super("LoadLargeBitmap", "Load large raw bitmap");
        }

        void onInit(Context context) {
            mContext = context;
        }

        boolean onRun() {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE;
            Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(),
                    R.drawable.wallpaper_goldengate, opts);
            bm.recycle();
            return true;
        }
    }

    static class LoadSmallScaledBitmapOp extends Op {
        Context mContext;

        LoadSmallScaledBitmapOp() {
            super("LoadSmallScaledBitmap", "Load small raw bitmap that is scaled for density");
        }

        void onInit(Context context) {
            mContext = context;
        }

        boolean onRun() {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE;
            Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(),
                    R.drawable.stat_sample_scale, opts);
            bm.recycle();
            return true;
        }
    }

    static class LoadLargeScaledBitmapOp extends Op {
        Context mContext;

        LoadLargeScaledBitmapOp() {
            super("LoadLargeScaledBitmap", "Load large raw bitmap that is scaled for density");
        }

        void onInit(Context context) {
            mContext = context;
        }

        boolean onRun() {
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE;
            Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(),
                    R.drawable.wallpaper_goldengate_scale, opts);
            bm.recycle();
            return true;
        }
    }
}