diff --git a/mercurial/configitems.toml b/mercurial/configitems.toml
index d81714a1c88d5143d3999afaa6e4eab4f32f590e_bWVyY3VyaWFsL2NvbmZpZ2l0ZW1zLnRvbWw=..3c9d67fc17b5b00c043819644f2b77c51b5e405a_bWVyY3VyaWFsL2NvbmZpZ2l0ZW1zLnRvbWw= 100644
--- a/mercurial/configitems.toml
+++ b/mercurial/configitems.toml
@@ -1801,6 +1801,10 @@
 
 [[items]]
 section = "profiling"
+name = "output-dir"
+
+[[items]]
+section = "profiling"
 name = "showmax"
 default = 0.999
 
diff --git a/mercurial/helptext/config.txt b/mercurial/helptext/config.txt
index d81714a1c88d5143d3999afaa6e4eab4f32f590e_bWVyY3VyaWFsL2hlbHB0ZXh0L2NvbmZpZy50eHQ=..3c9d67fc17b5b00c043819644f2b77c51b5e405a_bWVyY3VyaWFsL2hlbHB0ZXh0L2NvbmZpZy50eHQ= 100644
--- a/mercurial/helptext/config.txt
+++ b/mercurial/helptext/config.txt
@@ -2088,6 +2088,12 @@
     file exists, it is replaced. (default: None, data is printed on
     stderr)
 
+``output-dir``
+    Directory in which profiling data or report should be saved. The data will
+    be written to a file with the naming scheme "hg-profile-{TIMESTAMP}-{PID}".
+    If both ``output`` and ``output-dir`` are specified, ``output`` will take
+    precedence.
+
 ``sort``
     Sort field.  Specific to the ``ls`` instrumenting profiler.
     One of ``callcount``, ``reccallcount``, ``totaltime`` and
diff --git a/mercurial/profiling.py b/mercurial/profiling.py
index d81714a1c88d5143d3999afaa6e4eab4f32f590e_bWVyY3VyaWFsL3Byb2ZpbGluZy5weQ==..3c9d67fc17b5b00c043819644f2b77c51b5e405a_bWVyY3VyaWFsL3Byb2ZpbGluZy5weQ== 100644
--- a/mercurial/profiling.py
+++ b/mercurial/profiling.py
@@ -8,6 +8,7 @@
 from __future__ import annotations
 
 import contextlib
+import datetime
 import os
 import signal
 import subprocess
@@ -290,6 +291,17 @@
 
         self._output = self._ui.config(b'profiling', b'output')
 
+        if not self._output:
+            output_dir = self._ui.config(b'profiling', b'output-dir')
+            if output_dir:
+                util.makedirs(output_dir)
+                pid = os.getpid()
+                timestamp = encoding.strtolocal(
+                    datetime.datetime.utcnow().strftime("%Y%m%dT%H%M%S%fZ")
+                )
+                filename = b"hg-profile-%s-%d" % (timestamp, pid)
+                self._output = os.path.join(output_dir, filename)
+
         try:
             if self._output == b'blackbox':
                 self._fp = util.stringio()