Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-16 08:52:44

0001 //------------------------------- -*- C++ -*- -------------------------------//
0002 // Copyright Celeritas contributors: see top-level COPYRIGHT file for details
0003 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
0004 //---------------------------------------------------------------------------//
0005 //! \file corecel/sys/ScopedMem.hh
0006 //---------------------------------------------------------------------------//
0007 #pragma once
0008 
0009 #include <string_view>
0010 
0011 #include "corecel/Config.hh"
0012 
0013 #include "corecel/cont/InitializedValue.hh"
0014 
0015 #include "MemRegistry.hh"
0016 
0017 namespace celeritas
0018 {
0019 //---------------------------------------------------------------------------//
0020 /*!
0021  * Record the change in memory usage between construction and destruction.
0022  *
0023  * \code
0024     {
0025       ScopedMem record_mem("create objects");
0026       this->create_stuff();
0027     }
0028    \endcode
0029  *
0030  * This class is \em not thread safe because it writes to a shared global
0031  * index.  In a multithreaded environment a "null" scoped memory can be used:
0032  * \code
0033  * {
0034      auto record_mem = (stream_id == StreamId{0} ? ScopedMem{"label"}
0035                                                  : ScopedMem{});
0036      this->do_stuff();
0037  * }
0038  * \endcode
0039  *
0040  * \note The memory reported will likely only be valid if running a single
0041  * task on the GPU, because the start and stop values are per \em GPU rather
0042  * than per \em process. Be wary of the result.
0043  */
0044 class ScopedMem
0045 {
0046   public:
0047     // Default constructor for "null-op" recording
0048     ScopedMem() = default;
0049 
0050     // Construct with name and registries
0051     ScopedMem(std::string_view label, MemRegistry* registry);
0052 
0053     //! Construct with name and default registry
0054     explicit ScopedMem(std::string_view label)
0055         : ScopedMem{label, &celeritas::mem_registry()}
0056     {
0057     }
0058 
0059     // Register data on destruction
0060     ~ScopedMem() noexcept(!CELERITAS_DEBUG);
0061 
0062     //! Prevent copying but allow moving
0063     CELER_DEFAULT_MOVE_DELETE_COPY(ScopedMem);
0064 
0065   private:
0066     using value_type = KibiBytes::value_type;
0067 
0068     InitializedValue<MemRegistry*> registry_;
0069     MemUsageId id_;
0070     value_type cpu_start_hwm_{0};
0071     value_type gpu_start_used_{0};
0072 };
0073 
0074 //---------------------------------------------------------------------------//
0075 }  // namespace celeritas