profiler.cpp 2.3 KB
Newer Older
1
/**
M
Megvii Engine Team 已提交
2 3
 * \file imperative/src/impl/profiler.cpp
 * MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
4
 *
5
 * Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
6
 *
M
Megvii Engine Team 已提交
7 8 9
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 11 12 13
 */

#include "megbrain/imperative/profiler.h"

14 15
#include <chrono>

16 17 18
#include "megbrain/imperative/ops/opr_attr.h"
#include "megbrain/imperative/physical_tensor.h"

19 20
#include "megbrain/plugin/opr_footprint.h"

21
#include "./function_hook.h"
22
#include "./event_pool.h"
23 24
#include "./op_trait.h"

25 26
#include "./profiler/formats.h"

27 28 29
namespace mgb {
namespace imperative {

30 31
profiler::Time Timer::record_host() {
    return std::chrono::high_resolution_clock::now();
32 33
}

34
std::shared_ptr<CompNode::Event> Timer::record_device(CompNode device) {
35 36 37
    auto event = EventPool::with_timer().alloc_shared(device);
    event->record();
    return event;
38 39
}

40
std::vector<Profiler::entry_t> Profiler::sm_records;
41 42 43 44
Profiler::options_t Profiler::sm_profile_options;
std::mutex Profiler::sm_mutex;
std::unordered_map<std::thread::id, Profiler*> Profiler::sm_profilers;
Timer Profiler::sm_timer;
45
profiler::HostTime Profiler::sm_start_at = profiler::HostTime::min();
46 47 48 49 50 51 52 53
std::atomic_uint64_t Profiler::sm_last_id = 0;
bool Profiler::sm_profiling = false;
thread_local std::unique_ptr<Profiler> Profiler::tm_profiler = std::make_unique<Profiler>();
std::atomic_size_t Profiler::sm_preferred_capacity;

auto Profiler::get_thread_dict() -> thread_dict_t {
    thread_dict_t thread_dict;
    for (auto&& [tid, profiler]: sm_profilers) {
54
        thread_dict[tid] = sys::get_thread_name(tid);
55 56
    }
    return thread_dict;
57 58
}

59
void Profiler::dump_profile(std::string basename, std::string format, bundle_t result) {
60 61 62 63
    static std::unordered_map<std::string, void(*)(std::string, bundle_t)> format_table = {
        {"chrome_timeline.json", profiler::dump_chrome_timeline},
        {"memory_flow.svg", profiler::dump_memory_flow},
    };
64 65
    auto iter = format_table.find(format);
    if (iter == format_table.end()) {
66 67
        mgb_log_error("unsupported profiling format %s", format.c_str());
    }
68
    return (iter->second)(basename, result);
69 70
}

71 72 73
}  // namespace imperative

}  // namespace mgb