HelloWorld

The following is a "Hello World" sample of Ascend C. It showcases the basic syntax of an Ascend C kernel function (entry point function implemented on the device) and how the function is called.

  • In the following code of the kernel implementation file hello_world.cpp, the core logic of the kernel function hello_world is to print the "Hello World" string. hello_world_do encapsulates the kernel function calling program using the kernel launch symbol <<<>>>.
    #include "kernel_operator.h"
    extern "C" __global__ __aicore__ void hello_world()
    {
        AscendC::printf("Hello World!!!\n");
    }
    
    void hello_world_do(uint32_t blockDim, void* stream)
    {
        hello_world<<<blockDim, nullptr, stream>>>();
    }
  • The main.cpp code of the program that calls the kernel function is as follows (code comments are provided for better understanding of the main process):
    #include "acl/acl.h"
    extern void hello_world_do(uint32_t coreDim, void* stream);
    
    int32_t main(int argc, char const *argv[])
    {
        // Initialize AscendCL.
        aclInit(nullptr);
        // Allocate runtime resources.
        int32_t deviceId = 0;
        aclrtSetDevice(deviceId);
        aclrtStream stream = nullptr;
        aclrtCreateStream(&stream);
    
        // Set the number of cores used in compute to 8.
        constexpr uint32_t blockDim = 8;
        // Use the kernel launch symbol <<<>>> to call the kernel function. <<<>>> is encapsulated in hello_world_do.
        hello_world_do(blockDim, stream);
        aclrtSynchronizeStream(stream);
        // Destroy resources and deinitialize AscendCL.
        aclrtDestroyStream(stream);
        aclrtResetDevice(deviceId);
        aclFinalize();
        return 0;
    }

Use the following code project to organize the preceding files. Click here to obtain the sample project and configure the AI processor model and software package installation path in the CMakeLists.txt file by referring to the README file.

|-- CMakeLists.txt                                        // CMake compilation configuration file
|-- hello_world.cpp                                       // Kernel implementation
|-- main.cpp                                              // Main program to be called in the kernel function
|-- run.sh                                                // One-click compilation and running of the script

Run the following script to compile and run the sample program:

bash run.sh -v <soc_version>

The AI processor model <soc_version> can be obtained in the following ways:

  • Run the npu-smi info command on the server where the Ascend AI Processor is installed to obtain the Chip Name information. The actual value is AscendChip Name. For example, if Chip Name is xxxyy, the actual value is Ascendxxxyy.

This sample schedules eight cores and prints the core ID and "Hello World" message of each core.