"Hello world" in C++ AMP

We think of our matrix multiplication example as "Hello world", but it didn't sit quite well with me. It was missing the essential ingredients for a "Hello world" demo which are: to be simple, require a complete code listing, fit on a single slide, and output the text "Hello world". So in this blog post I'll share an alternative one that has those ingredients.


In Visual Studio 11 Beta (or later)

  1. Select "File" -> "New" -> "Project..." menu
  2. Select the "Empty Project" template and press "OK"
  3. Select the "Project" -> "Add New Item..." menu
  4. Select the "C++ File (.cpp)" item template and press "Add"

You now have an empty "Source.cpp" code file and have made no changes to any configuration of the project system or the compiler.

"Hello world" code

Type in (or copy paste) the following 14 lines of simplistic code and you are done!

   #include <iostream> 
  #include <amp.h> 
  using namespace concurrency; 
  int main() 
    int v[11] = {'G', 'd', 'k', 'k', 'n', 31, 'v', 'n', 'q', 'k', 'c'};

    array_view<int> av(11, v); 
    parallel_for_each(av.extent, [=](index<1> idx) restrict(amp) 
      av[idx] += 1; 

    for(unsigned int i = 0; i < 11; i++) 
      std::cout << static_cast<char>(av[i]); 

...and this is the "Hello world" output when run from the command line.

Hello world


The naive code above does not exhibit any performance benefits compared to a serial CPU implementation. The reason is that the amount of data is not large enough and the body of the loop is not performing expensive operations, to pay for the synchronization and data transfer overhead. The code does serve its purpose of understanding the main elements of the C++ AMP programming model, and that is left as an exercise to the reader; to aid you with that exercise, the program is using: index, extent, restrict, parallel_for_each, and array_view. You can also watch a screencast introducing these with the "Hello World" example.