midout.cpp 2.2 KB
Newer Older
J
jiakai 已提交
1 2
#include "midout.h"

3 4 5 6
// to avoid linking error for empty lib on some stupid platforms
void midout_empty() {
}

J
jiakai 已提交
7
#ifdef MIDOUT_PROFILING
J
jiakai 已提交
8 9
#pragma message "midout profiling enabled"

J
jiakai 已提交
10
#include <string>
J
jiakai 已提交
11 12 13
#include <vector>
#include <unordered_set>
#include <algorithm>
J
jiakai 已提交
14
#include <mutex>
J
jiakai 已提交
15 16 17 18 19 20 21

#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <sys/types.h>
#include <unistd.h>
Z
zengping 已提交
22
#include <errno.h>
J
jiakai 已提交
23 24 25 26

namespace {
    class UsedTypes {
        std::unordered_set<const char*> m_types;
J
jiakai 已提交
27
        std::mutex m_mtx;
J
jiakai 已提交
28 29 30 31

        public:

            void add(const char *type) {
J
jiakai 已提交
32
                std::lock_guard<std::mutex> guard{m_mtx};
J
jiakai 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
                m_types.insert(type);
            }

            ~UsedTypes() {
                auto output_fname = getenv("MIDOUT_OUTPUT");
                char output_fname_storage[256];
                if (!output_fname) {
                    output_fname = output_fname_storage;
                    snprintf(output_fname, sizeof(output_fname_storage),
                            "midout_trace.%d", static_cast<int>(getpid()));
                }
                FILE *fout = fopen(output_fname, "w");
                if (!fout) {
                    fprintf(stderr,
                            "midout: failed to open output file %s: %s\n",
                            output_fname, strerror(errno));
                }
J
jiakai 已提交
50
                fprintf(fout, "midout_trace v1\n");
J
jiakai 已提交
51 52 53
                std::vector<std::string> sorted_types;
                sorted_types.reserve(m_types.size());
                for (auto &&i: m_types) {
J
jiakai 已提交
54
                    sorted_types.emplace_back(i);
J
jiakai 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68
                }
                std::sort(sorted_types.begin(), sorted_types.end());
                for (auto &&i: sorted_types) {
                    fputs(i.c_str(), fout);
                    fputc('\n', fout);
                }
                fclose(fout);
                fprintf(stderr, "midout: %zu items written to %s\n",
                        sorted_types.size(), output_fname);
            }
    };
}

void midout::on_region_used(const std::type_info &type) {
J
jiakai 已提交
69 70
    static UsedTypes used_types;
    used_types.add(type.name());
J
jiakai 已提交
71 72 73
}

#endif  // MIDOUT_PROFILING
J
jiakai 已提交
74 75 76 77

#ifdef MIDOUT_GENERATED
#pragma message "stripping by midout enabled"
#endif