---
title: 局部采集Profiling数据（调用Profiler类方式）
description: "开发者可通过调用npu_bridge.profiler.profiler类实现局部采集性能数据的功能，即仅Profiler类作用域下的命令才会开启性能数据采集功能。"
url: https://www.hiascend.com/document/detail/zh/TensorFlowCommercial/latest/migration/tfmigr1/tfmigr1_000061.html
sourcePath: /source/zh/TensorFlowCommercial/900/migration/tfmigr1/tfmigr1_000061.html
indexId: 788220ade15129fe0a6fc542c43d71035b5c6458733a95cfdc4319e19f63b2fc73
---
# 局部采集Profiling数据（调用Profiler类方式）

开发者可通过调用npu_bridge.profiler.profiler类实现局部采集性能数据的功能，即仅Profiler类作用域下的命令才会开启性能数据采集功能。

下面介绍如何通过调用Profiler类实现采集局部性能数据的功能。

1. 引入Profiler类。
  1 from npu_bridge.npu_init import *

2. 通过with语句调用Profiler类，并将需要做性能数据采集的操作包含在Profiler类的作用域内。
  如下是一段简单的示例代码片段，此代码片段构造了一个包含add算子的图，并在session中执行此图。其中sess.run(add, ...)函数在Profiler的作用域内，所以会执行L1级别的性能数据采集，并统计各种计算类指标占比统计，性能采集数据存储在当前脚本执行路径下。 1 2 3 4 5 6 7 8 a = tf.placeholder(tf.int32, (None,None)) b = tf.constant([[1,2],[2,3]], dtype=tf.int32, shape=(2,2)) c = tf.placeholder(tf.int32, (None,None)) add = tf.add(a, b) with tf.Session(config=session_config, graph=g) as sess: with profiler.Profiler(level="L1", aic_metrics="ArithmeticUtilization", output_path = "./"): result=sess.run(add, feed_dict={a: [[-20, 2],[1,3]],c: [[1],[-21]]})

  当前，开发者可以采集指定step的性能数据，只需要将指定的step操作定义在相应的Profiler作用域内即可，如下所示：

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 a=tf.placeholder(tf.int32, (None,None)) b=tf.constant([[1,2],[2,3]], dtype=tf.int32, shape=(2,2)) c = tf.placeholder(tf.int32, (None,None)) d = tf.constant([[1,2],[2,3]], dtype=tf.int32, shape=(2,2)) add1 = tf.add(a, b) add2 = tf.add(c, d) add3 = tf.add(add1, add2) with tf.Session(config=session_config, graph=g) as sess: with profiler.Profiler(level="L1", aic_metrics="PipeUtilization", output_path = "/home/test/profiling_data"): for i in range(2): result=sess.run(add1, feed_dict={a: [[-20],[1]]}) with profiler.Profiler(level="L1", aic_metrics="ArithmeticUtilization", output_path = "/home/test/profiling_data"): for i in range(4): result=sess.run(add3, feed_dict={a: [[-20, 2],[1,3]],c: [[1],[-21]]})

  关于Profiler类的使用约束可参见Profiler构造函数中的“约束说明”。
