profiler.py 2.1 KB
Newer Older
D
dangqingqing 已提交
1
import paddle.v2.fluid.core as core
D
dangqingqing 已提交
2
from contextlib import contextmanager
3
import os
D
dangqingqing 已提交
4

5
__all__ = ['CudaProfiler']
D
dangqingqing 已提交
6

D
dangqingqing 已提交
7
NVPROF_CONFIG = [
8 9 10 11
    "gpustarttimestamp",
    "gpuendtimestamp",
    "gridsize3d",
    "threadblocksize",
12 13 14 15 16 17
    "dynsmemperblock",
    "stasmemperblock",
    "regperthread",
    "memtransfersize",
    "memtransferdir",
    "memtransferhostmemtype",
18
    "streamid",
19
    "cacheconfigrequested",
D
dangqingqing 已提交
20 21
    "cacheconfigexecuted",
    "countermodeaggregate",
22
    "enableonstart 0",
23
    "active_warps",
D
dangqingqing 已提交
24
    "active_cycles",
25 26 27
]


D
dangqingqing 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
@contextmanager
def cuda_profiler(output_file, output_mode=None, config=None):
    """The CUDA profiler.
    This fuctions is used to profile CUDA program by CUDA runtime application
    programming interface. The profiling result will be written into
    `output_file` with Key-Value pair format or Comma separated values format.
    The user can set the output mode by `output_mode` argument and set the
    counters/options for profiling by `config` argument. The default config
    is ['gpustarttimestamp', 'gpustarttimestamp', 'gridsize3d',
    'threadblocksize', 'streamid', 'enableonstart 0', 'conckerneltrace'].

    Args:
        output_file (string) : The output file name, the result will be
            written into this file.
        output_mode (string) : The output mode has Key-Value pair format and
            Comma separated values format. It should be 'kvp' or 'csv'.
44 45
        config (list of string) : The profiler options and counters can refer
            to "Compute Command Line Profiler User Guide".
D
dangqingqing 已提交
46 47 48
    """
    if output_mode is None:
        output_mode = 'csv'
D
dangqingqing 已提交
49 50 51
    if output_mode not in ['kvp', 'csv']:
        raise ValueError("The output mode must be 'kvp' or 'csv'.")
    config = NVPROF_CONFIG if config is None else config
52 53 54 55
    config_file = 'nvprof_config_file'
    with open(config_file, 'wb') as fp:
        fp.writelines(["%s\n" % item for item in config])
    core.nvprof_init(output_file, output_mode, config_file)
D
dangqingqing 已提交
56
    # Enables profiler collection by the active CUDA profiling tool.
D
dangqingqing 已提交
57
    core.nvprof_start()
D
dangqingqing 已提交
58 59
    yield
    # Disables profiler collection.
D
dangqingqing 已提交
60
    core.nvprof_stop()
61
    os.remove(config_file)