You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

cpu_affinity.cpp 2.4 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * \file example/cpp_example/cpu_affinity.cpp
  3. * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  4. *
  5. * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  6. *
  7. * Unless required by applicable law or agreed to in writing,
  8. * software distributed under the License is distributed on an
  9. * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. */
  11. #include "../example.h"
  12. #if LITE_BUILD_WITH_MGE
  13. using namespace lite;
  14. using namespace example;
  15. bool lite::example::cpu_affinity(const Args& args) {
  16. std::string network_path = args.model_path;
  17. std::string input_path = args.input_path;
  18. //! create and load the network
  19. std::shared_ptr<Network> network = std::make_shared<Network>();
  20. //! run with multi theads
  21. Runtime::set_cpu_threads_number(network, 4);
  22. network->load_model(network_path);
  23. std::vector<int> core_ids = {0, 1, 2, 3};
  24. auto affinity = [core_ids](int id) {
  25. //! add user define affinity function
  26. set_cpu_affinity({core_ids[id]});
  27. printf("set thread id = %d with the affinity of core %d.\n", id, core_ids[id]);
  28. };
  29. Runtime::set_runtime_thread_affinity(network, affinity);
  30. //! set input data to input tensor
  31. std::shared_ptr<Tensor> input_tensor = network->get_input_tensor(0);
  32. //! copy or forward data to network
  33. size_t length = input_tensor->get_tensor_total_size_in_byte();
  34. void* dst_ptr = input_tensor->get_memory_ptr();
  35. auto src_tensor = parse_npy(input_path);
  36. void* src = src_tensor->get_memory_ptr();
  37. memcpy(dst_ptr, src, length);
  38. //! forward
  39. network->forward();
  40. network->wait();
  41. //! get the output data or read tensor set in network_in
  42. std::shared_ptr<Tensor> output_tensor = network->get_output_tensor(0);
  43. void* out_data = output_tensor->get_memory_ptr();
  44. size_t out_length = output_tensor->get_tensor_total_size_in_byte() /
  45. output_tensor->get_layout().get_elem_size();
  46. printf("length=%zu\n", length);
  47. float max = -1.0f;
  48. float sum = 0.0f;
  49. for (size_t i = 0; i < out_length; i++) {
  50. float data = static_cast<float*>(out_data)[i];
  51. sum += data;
  52. if (max < data)
  53. max = data;
  54. }
  55. printf("max=%e, sum=%e\n", max, sum);
  56. return true;
  57. }
  58. #endif
  59. // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台