• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2023 Huawei Technologies Co., Ltd
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef MINDSPORE_MINDSPORE_CCSRC_DEBUG_DATA_DUMP_CSV_WRITER_H_
18 #define MINDSPORE_MINDSPORE_CCSRC_DEBUG_DATA_DUMP_CSV_WRITER_H_
19 
20 #include <memory>
21 #include <string>
22 #include <fstream>
23 #include <mutex>
24 #include <shared_mutex>
25 #include "utils/ms_utils.h"
26 
27 namespace mindspore {
28 class CsvWriter {
29  public:
30   static CsvWriter &GetInstance();
31 
32   CsvWriter() = default;
33   ~CsvWriter();
34   DISABLE_COPY_AND_ASSIGN(CsvWriter)
35   bool OpenFile(const std::string &path, const std::string &header = "", bool trunc = false);
36   void CloseFile() noexcept;
37   template <typename T>
38   void WriteToCsv(const T &val, bool end_line = false) {
39     std::shared_lock<std::shared_mutex> lock(write_mutex_);
40     file_ << val;
41     if (end_line) {
42       file_ << kEndLine;
43       (void)file_.flush();
44     } else {
45       file_ << kSeparator;
46     }
47   }
48 
49  private:
50   const std::string kSeparator = ",";
51   const std::string kEndLine = "\n";
52   std::ofstream file_;
53   std::string file_path_str_ = "";
54   std::shared_mutex write_mutex_;
55 };
56 }  // namespace mindspore
57 #endif  // MINDSPORE_MINDSPORE_CCSRC_DEBUG_DATA_DUMP_CSV_WRITER_H_
58