HelloWorld

This example shows how to use Ascend C to compile a simple "Hello World" program, including the implementation of the kernel function (entry function implemented on the device), calling process, and complete steps for compilation and running. With this example, you can quickly understand the basic development process of Ascend C. For details about the complete example, click LINK.

The code file hello_world.asc contains the implementation of the kernel function and the main function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Header file to be included in the application on the host
#include "acl/acl.h"
// Header file to be included in the kernel
#include "kernel_operator.h"
__global__ __vector__ void hello_world()
{
 
    AscendC::printf("[Block (%lu/%lu)]: Hello World!!!\n", AscendC::GetBlockIdx(), AscendC::GetBlockNum());
}

int32_t main(int argc, char const *argv[])
{
    // Initialization
    aclInit(nullptr);
    // Allocate runtime resources.
    int32_t deviceId = 0;
    aclrtSetDevice(deviceId);
    aclrtStream stream = nullptr;
    aclrtCreateStream(&stream);

    // Set the number of cores involved in the computation to 8. (The number of cores can be set as required.)
    constexpr uint32_t numBlocks = 8;
    // Call the kernel function using the kernel launch symbol <<<>>>.
    hello_world<<<numBlocks, nullptr, stream>>>();
    aclrtSynchronizeStream(stream);
    // Destroy resources and perform deinitialization.
    aclrtDestroyStream(stream);
    aclrtResetDevice(deviceId);
    aclFinalize();
    return 0;
}

After the code is implemented, you can compile the preceding code in either of the following ways:

  • This sample supports only the following models:
    • Atlas 350 Accelerator Card
    • Atlas A3 training product/Atlas A3 inference product
    • Atlas A2 training product/Atlas A2 inference product
  • In the compilation command, --npu-arch is used to specify the architecture version of the NPU. The string following dav- is the architecture version number. You need to replace the architecture version number with the actual one. For details about the mapping between the AI processor model and architecture version number, see Table 1.

The running result is as follows. In this example, eight cores are scheduled, and the core IDs and "Hello World!!!" are printed.

[Block (0/8)]: Hello World!!!
[Block (1/8)]: Hello World!!!
[Block (2/8)]: Hello World!!!
[Block (3/8)]: Hello World!!!
[Block (4/8)]: Hello World!!!
[Block (5/8)]: Hello World!!!
[Block (6/8)]: Hello World!!!
[Block (7/8)]: Hello World!!!