Imported Upstream version 1.12.0
[platform/core/ml/nnfw.git] / runtime / libs / benchmark / src / CsvWriter.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
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 #include "benchmark/CsvWriter.h"
18 #include <cassert>
19
20 namespace
21 {
22
23 const std::vector<std::string> csv_header{
24 #include "benchmark/CsvHeader.lst"
25 };
26
27 } // namespace
28
29 namespace benchmark
30 {
31
32 CsvWriter::CsvWriter(const std::string &csv_filename) : CsvWriter(csv_filename, csv_header)
33 {
34   // DO NOTHING
35 }
36
37 CsvWriter::CsvWriter(const std::string &csv_filename, const std::vector<std::string> &header)
38   : _ofs(csv_filename), _header_size(header.size()), _col_idx(0), _row_idx(0)
39 {
40   assert(csv_filename.empty() == false);
41   assert(header.size() != 0);
42   assert(_ofs.is_open());
43
44   writeHeader(header);
45 }
46
47 CsvWriter::~CsvWriter()
48 {
49   if (_ofs.is_open())
50     _ofs.close();
51 }
52
53 void CsvWriter::writeHeader(const std::vector<std::string> &header)
54 {
55   for (const auto &col : header)
56     write(col);
57 }
58
59 void CsvWriter::postWrite()
60 {
61   if (++_col_idx == _header_size)
62   {
63     _ofs << newline;
64     _row_idx += 1;
65     _col_idx = 0;
66   }
67   else
68   {
69     _ofs << delimiter;
70   }
71 }
72
73 void CsvWriter::write(const std::string &val)
74 {
75   _ofs << val;
76   postWrite();
77 }
78
79 void CsvWriter::write(double val)
80 {
81   _ofs << val;
82   postWrite();
83 }
84
85 void CsvWriter::write(uint32_t val)
86 {
87   _ofs << val;
88   postWrite();
89 }
90
91 void CsvWriter::write(char val)
92 {
93   _ofs << val;
94   postWrite();
95 }
96
97 bool CsvWriter::done() { return (_col_idx == 0) && (_row_idx == 2); }
98
99 CsvWriter &operator<<(CsvWriter &csvw, const std::string &val)
100 {
101   csvw.write(val);
102   return csvw;
103 }
104
105 CsvWriter &operator<<(CsvWriter &csvw, double val)
106 {
107   csvw.write(val);
108   return csvw;
109 }
110
111 CsvWriter &operator<<(CsvWriter &csvw, uint32_t val)
112 {
113   csvw.write(val);
114   return csvw;
115 }
116
117 CsvWriter &operator<<(CsvWriter &csvw, char val)
118 {
119   csvw.write(val);
120   return csvw;
121 }
122
123 } // namespace benchmark