Analysis Software
Documentation for sPHENIX simulation software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
CpuVector.hpp
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file CpuVector.hpp
1 // This file is part of the Acts project.
2 //
3 // Copyright (C) 2020 CERN for the benefit of the Acts project
4 //
5 // This Source Code Form is subject to the terms of the Mozilla Public
6 // License, v. 2.0. If a copy of the MPL was not distributed with this
7 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 
9 #pragma once
10 
11 #include "Acts/Plugins/Cuda/Utilities/CudaVector.cu"
12 
13 #include <cstring>
14 
15 namespace Acts {
16 
17 template <typename var_t>
18 class CudaVector;
19 
20 template <typename var_t>
21 class CpuVector {
22  public:
23  CpuVector() = delete;
24  CpuVector(size_t size, bool pinned = false) {
25  m_size = size;
26  m_pinned = pinned;
27  if (!pinned) {
28  m_hostPtr = new var_t[m_size];
29  } else if (pinned) {
30  cudaMallocHost(&m_hostPtr, m_size * sizeof(var_t));
31  }
32  }
33 
34  CpuVector(size_t size, CudaVector<var_t>* cuVec, bool pinned = false) {
35  m_size = size;
36  m_pinned = pinned;
37  if (!pinned) {
38  m_hostPtr = new var_t[m_size];
39  } else if (pinned) {
40  cudaMallocHost(&m_hostPtr, m_size * sizeof(var_t));
41  }
42  cudaMemcpy(m_hostPtr, cuVec->get(), m_size * sizeof(var_t),
43  cudaMemcpyDeviceToHost);
44  }
45 
47  if (!m_pinned) {
48  delete m_hostPtr;
49  } else if (m_pinned && m_hostPtr) {
50  cudaFreeHost(m_hostPtr);
51  }
52  }
53 
54  var_t* get(size_t offset = 0) { return m_hostPtr + offset; }
55 
56  void set(size_t offset, var_t val) { m_hostPtr[offset] = val; }
57 
58  void copyD2H(var_t* devPtr, size_t len, size_t offset) {
59  cudaMemcpy(m_hostPtr + offset, devPtr, len * sizeof(var_t),
60  cudaMemcpyDeviceToHost);
61  }
62 
63  void copyD2H(var_t* devPtr, size_t len, size_t offset, cudaStream_t* stream) {
64  cudaMemcpyAsync(m_hostPtr + offset, devPtr, len * sizeof(var_t),
65  cudaMemcpyDeviceToHost, *stream);
66  }
67 
68  void zeros() { memset(m_hostPtr, 0, m_size * sizeof(var_t)); }
69 
70  private:
71  var_t* m_hostPtr = nullptr;
72  size_t m_size;
73  bool m_pinned;
74 };
75 
76 } // namespace Acts