Publishing 2019 R1 content
[platform/upstream/dldt.git] / inference-engine / samples / common / samples / csv_dumper.hpp
1 // Copyright (C) 2019 Intel Corporation
2 // SPDX-License-Identifier: Apache-2.0
3 //
4
5 #pragma once
6
7 #include <fstream>
8 #include <iostream>
9 #include <sstream>
10 #include <string>
11 #include <time.h>
12
13 #include <samples/slog.hpp>
14
15 /**
16  * @class CsvDumper
17  * @brief A CsvDumper class provides functionality for dumping the values in CSV files
18  */
19 class CsvDumper {
20     std::ofstream file;
21     std::string filename;
22     bool canDump = true;
23     char delimiter = ';';
24
25     std::string generateFilename() {
26         std::stringstream filename;
27         filename << "dumpfile-";
28         filename << time(nullptr);
29         filename << ".csv";
30         return filename.str();
31     }
32
33 public:
34     /**
35      * @brief A constructor. Disables dumping in case dump file cannot be created
36      * @param enabled - True if dumping is enabled by default.
37      * @param name - name of file to dump to. File won't be created if first parameter is false.
38      */
39     explicit CsvDumper(bool enabled = true, const std::string& name = "") : canDump(enabled) {
40         if (!canDump) {
41             return;
42         }
43         filename = (name == "" ? generateFilename() : name);
44         file.open(filename, std::ios::out);
45         if (!file) {
46             slog::warn << "Cannot create dump file! Disabling dump." << slog::endl;
47             canDump = false;
48         }
49     }
50
51     /**
52      * @brief Sets a delimiter to use in csv file
53      * @param c - Delimiter char
54      * @return
55      */
56     void setDelimiter(char c) {
57         delimiter = c;
58     }
59
60     /**
61      * @brief Overloads operator to organize streaming values to file. Does nothing if dumping is disabled
62      *        Adds delimiter at the end of value provided
63      * @param add - value to add to dump
64      * @return reference to same object
65      */
66     template<class T>
67     CsvDumper& operator<<(const T& add) {
68         if (canDump) {
69             file << add << delimiter;
70         }
71         return *this;
72     }
73
74     /**
75      * @brief Finishes line in dump file. Does nothing if dumping is disabled
76      */
77     void endLine() {
78         if (canDump) {
79             file << "\n";
80         }
81     }
82
83     /**
84      * @brief Gets information if dump is enabled.
85      * @return true if dump is enabled and file was successfully created
86      */
87     bool dumpEnabled() {
88         return canDump;
89     }
90
91     /**
92      * @brief Gets name of a dump file
93      * @return name of a dump file
94      */
95     std::string getFilename() const {
96         return filename;
97     }
98 };