yse / easy_profiler

Lightweight profiler library for c++
MIT License
2.14k stars 184 forks source link

Run slower #193

Open Tianxiaomo opened 3 years ago

Tianxiaomo commented 3 years ago
import clang.cindex
from clang.cindex import Index
from clang.cindex import Config
from clang.cindex import CursorKind
from clang.cindex import TypeKind
from glob2 import glob

libclangPath = r'C:\Program Files\LLVM\bin\libclang.dll'
if Config.loaded == True:
    print("Config.loaded == True:")
else:
    Config.set_library_file(libclangPath)
    print("install path")

stmt = False

def preorder_travers_AST(cursor, stmt_list):
    for cur in cursor.get_children():
        # do something
        global stmt
        # print(cur.spelling, cur.location, cur.kind)
        if (cur.kind == CursorKind.FUNCTION_DECL or cur.kind == CursorKind.CXX_METHOD) and (
                cur.location.file.name[-2:] == ".c" or cur.location.file.name[-4:] == ".cpp"):
            print(cur.spelling, cur.kind, cur.type.kind, cur.location)
            stmt = True
        if stmt == True and cur.kind == CursorKind.COMPOUND_STMT:
            print(cur.spelling, cur.kind, cur.type.kind, cur.location)
            stmt_list.append((cur.location.line, cur.location.column))
            stmt = False
        preorder_travers_AST(cur, stmt_list)

def add_profiler_for_file(path, stmt_list):
    index = Index.create()
    tu = index.parse(path)
    tu = index.parse(path, ['c++', '-std=c++11', '-DCALL_METHOD=', '-D__linux__'])
    AST_root_node = tu.cursor
    preorder_travers_AST(AST_root_node, stmt_list)

def add_profiler(path, stmt_list):
    profiler_head = "#include <easy/profiler.h>\n"
    profiler = "EASY_FUNCTION();"
    try:
        data = open(path, "r").readlines()
    except:
        data = open(path, "r", encoding="utf-8").readlines()
    if data[0] == profiler_head:
        return

    for i, j in stmt_list:
        print(data[i - 1][j - 1])
        data[i - 1] = data[i - 1].replace("{", "{" + profiler)
    data.insert(0, profiler_head)

    f = open(path, "w+", encoding='utf-8')
    f.writelines(data)
    f.close()

if __name__ == "__main__":
    src_dir = "H:\xxxxxx"
    cpp_list = glob(src_dir + "\**\*.cpp")

    print(len(cpp_list))
    for i, file_path in enumerate(cpp_list):
        print(file_path)
        stmt_list = []
        add_profiler_for_file(file_path, stmt_list)
        print(stmt_list)
        add_profiler(file_path, stmt_list)

I use python script to add 'EASY_FUNCTION();' to each function.However, it took three times longer to run. It's confusing to me.