function::nsecs_to_string - Linux


function::nsecs_to_string converts nanoseconds to human-readable string representations. It’s a powerful tool for transforming timestamps into comprehensible formats.


nsecs_to_string(nanoseconds, granularity=6, short=False)


  • granularity: Sets the output precision in milliseconds (ms). Defaults to 6 (microsecond precision). Valid values are:
    • 0: nanoseconds (ns)
    • 3: milliseconds (ms)
    • 6: microseconds (µs)
    • 9: nanoseconds (ns)
  • short: Shorten the output string where applicable (e.g., "123 µs" instead of "123.000 µs").


Example 1: Convert to Microseconds

nsecs_to_string(1234567890)  # Output: "123.457 ms"

Example 2: Convert to Milliseconds with Shortened Output

nsecs_to_string(987654321000, granularity=3, short=True)  # Output: "98.765 s"

Example 3: Convert to Nanoseconds

nsecs_to_string(1234567890123, granularity=0)  # Output: "123,456,789 ns"

Common Issues

Issue: Output string is too precise or cluttered.
Solution: Adjust the granularity parameter to the desired level of detail.

Issue: Output string is not in the expected format.
Solution: Ensure that the correct granularity and short options are used.


function::nsecs_to_string integrates seamlessly with other timestamp manipulation commands, such as function::timestamp_now and date.

Example: Convert Timestamp to Human-Readable Format

human_string=$(function::nsecs_to_string ${timestamp})
echo "Current time: ${human_string}"

Related Commands

  • date: Command-line utility for manipulating and displaying dates and times.
  • function::timestamp_now: Get the current system time in nanoseconds.