---
title: 局部采集Profiling数据
description: "TF Adapter 2.x暂不支持局部采集Profiling数据，但开发者可通过compat.v1模块调用TF Adapter 1.x中的Profiler类，从而实现局部采集性能数据的功能，即仅Profiler类作用域下的命令才会开启性能数据采集功能。"
url: https://www.hiascend.com/document/detail/zh/TensorFlowCommercial/latest/migration/tfmigr2/tfmigr2_000073.html
sourcePath: /source/zh/TensorFlowCommercial/900/migration/tfmigr2/tfmigr2_000073.html
indexId: 0ea0f0bc8158764458c603f3b9bd4048851281839deb244f475c7fb5362430f673
---
# 局部采集Profiling数据

TF Adapter 2.x暂不支持局部采集Profiling数据，但开发者可通过compat.v1模块调用TF Adapter 1.x中的Profiler类，从而实现局部采集性能数据的功能，即仅Profiler类作用域下的命令才会开启性能数据采集功能。

关于Profiler类的详细介绍可参见Profiler构造函数(https://www.hiascend.comdocument/detail/zh/TensorFlowCommercial/900/migration/tfmigr1/tfmigr1_tfadapi_0096.html)。

下面介绍如何通过compat.v1模块调用TF Adapter 1.x的Profiler类实现采集局部性能数据的功能。

1. 引入Profiler类。
  1 2 3 import npu_device from npu_device.compat.v1.npu_init import * npu_device.compat.enable_v1() # 禁用TF2行为，启用TF1兼容模式

2. 通过with语句调用Profiler类，并将需要做性能数据采集的操作包含在Profiler类的作用域内。
如下是一段简单的示例代码片段，此代码片段构造了一个包含add算子的图，并在session中执行此图。其中sess.run(add, ...)函数在Profiler的作用域内，所以会执行L1级别的性能数据采集，并统计各种计算类指标占比，性能采集数据存储在当前脚本执行路径下。```
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.compat.v1.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]]})
```


当前，开发者可以采集指定steps的性能数据，只需要将指定的steps操作定义在相应的Profiler作用域内即可，如下所示：
```
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.compat.v1.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类需要通过with语句调用，性能数据采集功能会在对应的作用域内生效。
  - Profiler类仅支持session模式调用。
  - Profiler类不能嵌套使用。
    如下所示，是错误的调用方法。

    1 2 3 with profiler.Profiler(level="L1", aic_metrics="ArithmeticUtilization", output_path = "./"): with profiler.Profiler(level="L1", aic_metrics="ArithmeticUtilization", output_path = "./"): sess.run(add)

  - Profiler类不能与    “global_options > Profiling”
中的配置项“enable_profiling”、“profiling_config”以及环境变量“PROFILING_MODE”、“PROFILING_OPTIONS”同时使用，关于环境变量的详细说明可参见《环境变量参考(https://www.hiascend.com/document/detail/zh/canncommercial/900/maintenref/envvar/envref_07_0001.html)》。
  - Profiler类不支持多线程调用。
