Skip to content

Commit cd23961

Browse files
authored
Make format_with_precision thread-safe (#6)
* Add `diagham_command` to only create the command string. Also add option `wait` to `execute_diagham_script` to control whether the process should be waited for. * format * make format_with_precision thread-safe * format * fix dependency
1 parent 92de394 commit cd23961

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

Project.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@ Format = "1fa38f19-a742-5d3f-a2b9-30dd87b9d5f8"
99
Preferences = "21216c6a-2e73-6563-6e65-726566657250"
1010
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
1111
SparseArrays = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
12+
ThreadSafeDicts = "4239201d-c60e-5e0a-9702-85d713665ba7"
1213

1314
[compat]
1415
DelimitedFiles = "1"
1516
Format = "1.3.7"
1617
Preferences = "1.5.0"
1718
Printf = "1"
1819
SparseArrays = "1"
20+
ThreadSafeDicts = "0.1.6"
1921
julia = "1.10"

src/DiagHamInterface.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@ export write_to_txt
1212
export write_matrix_elements
1313

1414
using DelimitedFiles
15-
using Format: cfmt
15+
using Format
1616
using SparseArrays
1717
using Preferences
18+
using ThreadSafeDicts
1819

1920
include("utility/backup.jl")
2021
include("utility/diagham_path.jl")

src/utility/numbers.jl

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
1+
# Maps the format string (e.g. "%.5f") to the compiled formatter Function.
2+
const LOCAL_FORMAT_CACHE = ThreadSafeDict{String, Function}()
3+
14
"""
25
format_with_precision(x; atol=eps(float(T)), mode=:auto, maxdigits=20)
36
47
Format number `x` as a string with absolute precision `atol`.
58
Mode `:auto` uses `%f` for `[1e-3, 1e6)`, else `%e`. Use `:f` or `:e` to force format.
69
"""
710
function format_with_precision(x::T; atol = eps(float(T)), mode::Symbol = :auto, maxdigits::Int = 20) where {T <: Real}
8-
x == 0 && return "0.0"
11+
iszero(x) && return "0.0"
912
absx = abs(x)
1013
abs_atol = abs(atol)
1114

@@ -16,11 +19,21 @@ function format_with_precision(x::T; atol = eps(float(T)), mode::Symbol = :auto,
1619
log10_atol = log10(abs_atol)
1720
p = ceil(Int, exp10 - log10_atol)
1821
p = clamp(p, 0, maxdigits)
19-
return cfmt("%.$(p)e", x)
22+
23+
formatter = get_threadsafe_formatter("%.$(p)e")
24+
return formatter(x)
2025
else
2126
p = ceil(Int, -log10(abs_atol))
2227
p = clamp(p, 0, maxdigits)
23-
return cfmt("%.$(p)f", x)
28+
29+
formatter = get_threadsafe_formatter("%.$(p)f")
30+
return formatter(x)
31+
end
32+
end
33+
34+
function get_threadsafe_formatter(fmtstr::String)
35+
return get!(LOCAL_FORMAT_CACHE, fmtstr) do
36+
Format.generate_formatter(fmtstr)
2437
end
2538
end
2639

0 commit comments

Comments
 (0)