printf¶
Defined in header <Kokkos_Printf.hpp>since Kokkos 4.2 which is included from <Kokkos_Core.hpp>
Usage¶
Kokkos::printf("Hello World!");
Kokkos::printf("Pi is approx %.2f\n", 3.14159);
Kokkos::printf("Value at index %d: %f\n", i, data[i]);
Prints formatted output to the standard output stream (stdout). This
function can be called from both host and device code, including within
parallel kernels. The behavior is analogous to std::printf, but returns
void instead of an integer to ensure consistent behavior across backends.
Interface¶
-
template<typename ...Args>
KOKKOS_FUNCTION void printf(const char *format, Args... args);¶ Added in version 4.2.
- Parameters:
format – Null-terminated string specifying how to format the output, using format specifiers compatible with C
printfargs – Values to be printed according to the format string
- Returns:
void (unlike
std::printfwhich returns the number of characters written)
Format Specifiers¶
Supports standard C printf format specifiers:
%d,%i- signed integer%u- unsigned integer%f- floating point%e,%E- scientific notation%g,%G- shortest representation%s- string%p- pointer%x,%X- hexadecimalWidth, precision, and length modifiers (e.g.,
%.2f,%10d)
Example¶
Basic Usage¶
#include <Kokkos_Core.hpp>
int main(int argc, char* argv[]) {
Kokkos::initialize(argc, argv);
{
Kokkos::printf("Starting computation\n");
Kokkos::parallel_for("hello", 4, KOKKOS_LAMBDA(int i) {
Kokkos::printf("hello world from thread %d\n", i);
});
Kokkos::fence();
Kokkos::printf("Computation complete\n");
}
Kokkos::finalize();
}
Debugging Values¶
Kokkos::parallel_for("debug", n, KOKKOS_LAMBDA(int i) {
if (i < 5) { // Limit output for large arrays
Kokkos::printf("data[%d] = %.6f\n", i, data(i));
}
if (data(i) < 0) {
Kokkos::printf("Warning: negative value at index %d: %f\n", i, data(i));
}
});
Notes¶
Warning
Calling printf() from a kernel may affect register usage and
reduce performance. Use sparingly in performance-critical code.
See also¶
See also
- abort
Causes abnormal program termination with an error message
- KOKKOS_ASSERT
Conditionally aborts if a condition is false; useful for debugging