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.2 kB

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

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