context.h 1.9 KB
Newer Older
H
backup  
hjchen2 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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. */

#pragma once

17 18 19 20
#if _OPENMP
#include <omp.h>
#endif

H
backup  
hjchen2 已提交
21 22 23
#define MOBILE_MAX_CPU_NUM 8

namespace paddle_mobile {
24
namespace framework {
H
backup  
hjchen2 已提交
25

26
struct CPUContext {
H
backup  
hjchen2 已提交
27
 private:
28
  CPUContext() : num_cpus(4), num_threads(1) {
H
backup  
hjchen2 已提交
29 30
    // TODO(hjchen2)
    for (int i = 0; i < num_cpus; ++i) {
31 32
      cpu_frequencies[i] = 2400;      // 2400 MHz
      max_cpu_frequencies[i] = 2400;  // 2400 MHz
H
backup  
hjchen2 已提交
33 34 35 36 37 38 39 40
    }
    //    L1_cache = 32000;    // 32K
    L1_cache = 32 * 1024;
    L2_cache = 2000000;  // 2M
                         //    L2_cache = 512000;
  }

 public:
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
  void set_num_threads(int threads) {
#if _ONENMP
    omp_set_num_threads(threads);
    if (threads <= omp_get_max_threads()) {
      num_threads = threads;
    } else {
      num_threads = omp_get_max_threads();
    }
#endif
    num_threads = (num_threads > 1) ? num_threads : 1;
  }

  virtual ~CPUContext() {}

 public:
  static CPUContext* Context() {
    static CPUContext* ctx = new CPUContext;
H
backup  
hjchen2 已提交
58 59 60 61
    return ctx;
  }

  int num_cpus;
62 63 64
  int num_threads;
  int cpu_frequencies[MOBILE_MAX_CPU_NUM];
  int max_cpu_frequencies[MOBILE_MAX_CPU_NUM];
H
backup  
hjchen2 已提交
65 66 67 68 69

  int L1_cache;
  int L2_cache;
};

70
inline void set_global_num_threads(int threads) {
H
hjchen2 已提交
71
  CPUContext::Context()->set_num_threads(threads);
72 73 74 75 76 77 78
}

inline int get_global_num_threads() {
  return CPUContext::Context()->num_threads;
}

}  // namespace framework
H
backup  
hjchen2 已提交
79
}  // namespace paddle_mobile