---
title: 算子运行
description: "算子的计算算法实现通过Ascend C API来完成，而算子的加载调用则使用Runtime API来完成。本章节将结合核函数调用介绍CANN软件栈中Ascend C算子运行时常用的Runtime接口。Runtime接口更多信息与细节可以参考《Runtime运行时 API(https://www.hiascend.com/document/detail/zh/canncommercial/900/API/runtimeapi/aclcppdevg_03_1952.html)》。"
url: https://www.hiascend.com/document/detail/zh/canncommercial/latest/programug/Ascendcopdevg/atlas_ascendc_10_00043.html
sourcePath: /source/zh/canncommercial/900/programug/Ascendcopdevg/atlas_ascendc_10_00043.html
indexId: 2337a7d9064468ea76d8dc51cec49792fad5c853aaeed5d7c00b39904adffbb781
---
# 算子运行

算子的计算算法实现通过Ascend C API来完成，而算子的加载调用则使用Runtime API来完成。本章节将结合核函数调用介绍CANN软件栈中Ascend C算子运行时常用的Runtime接口。Runtime接口更多信息与细节可以参考《Runtime运行时 API(https://www.hiascend.com/document/detail/zh/canncommercial/900/API/runtimeapi/aclcppdevg_03_1952.html)》。

#### 加载和运行代码

加载和运行算子时，需要使用Runtime API，完成运行时管理和配置。主要流程和使用到的API如下：1. 初始化：aclInit。
2. 运行时资源申请：通过aclrtSetDevice和aclrtCreateStream分别申请Device、Stream运行管理资源。
3. 使用aclrtMallocHost分配Host内存，并进行数据初始化。
4. 使用aclrtMalloc分配Device内存，并通过aclrtMemcpy将数据从Host上拷贝到Device上，参与核函数计算。
5. 使用<<<>>>调用算子核函数。
6. 执行核函数后，将Device上的运算结果拷贝回Host。
7. 异步等待核函数执行完成：aclrtSynchronizeStream。
8. 资源释放：通过aclrtDestroyStream和aclrtResetDevice分别释放Stream、Device运行管理资源。
9. 去初始化：aclFinalize。


#### Kernel加载与执行的更多方式

Kernel的加载与执行也可以通过二进制加载方式实现，这是最底层的接口实现方式。内核调用符<<<...>>>为对底层接口的封装实现。使用时需要bisheng命令行编译将算子源文件编译为二进制.o文件，再通过aclrtLaunchKernelWithConfig等Kernel加载与执行接口完成算子调用。

- Kernel加载与执行接口的具体说明请参考“Kernel加载与执行(https://www.hiascend.comdocument/detail/zh/canncommercial/900/API/runtimeapi/aclcppdevg_03_0145.html)”章节。
- 关于更多bisheng命令行编译选项的使用介绍，SIMD编程、SIMD与SIMT混合编程场景请参考  常用的编译选项
， SIMT编程场景请参考  SIMT编程常用的编译选项
。
- SIMD编程、SIMD与SIMT混合编程场景完整样例请参考Kernel加载与执行（加载二进制）样例(https://gitee.com/ascend/samples/tree/master/operator/ascendc/0_introduction/3_add_kernellaunch/AddKernelInvocationAcl)，SIMT编程场景的样例请参考LINK(https://gitcode.com/cann/asc-devkit/tree/9.0.0/examples/03_simt_api/00_introduction/01_add)。

核函数的调用是异步的，核函数的调用结束后，控制权立刻返回给主机端，可以调用以下aclrtSynchronizeStream(https://www.hiascend.comdocument/detail/zh/canncommercial/900/API/runtimeapi/aclcppdevg_03_0076.html)函数来强制主机端程序等待所有核函数执行完毕。

```
aclError aclrtSynchronizeStream(aclrtStream stream);
```
