Skip to content

Commit

Permalink
@printf, @sprintf macros: new printf-like interface.
Browse files Browse the repository at this point in the history
From here on in, printf-like functionality is accessed by using
the @printf and @sprintf macros. Examples:

    julia> @printf("%d %f\n",123,pi)
    123 3.141593

    julia> sprint(io->@printf(io,"%d %f\n",123,pi))
    "123 3.141593\n"

    julia> @sprintf("%d %f\n",123,pi)
    "123 3.141593\n"

If the first argument to the @printf macro is a literal string then
it is interpreted as a format specification and the current output
stream is used for printing. Otherwise, the first argument is
evaluated and used as an IO handle for printing and the second
argument must be a literal format string. All following arguments
are evaluated and used as values to be printed.
  • Loading branch information
StefanKarpinski committed Aug 3, 2012
1 parent 3ae7ab3 commit 04f542d
Show file tree
Hide file tree
Showing 18 changed files with 49 additions and 48 deletions.
2 changes: 1 addition & 1 deletion base/grisu.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ macro grisu_ccall(value, mode, ndigits)
ccall(dlsym(Base.libgrisu, :grisu), Void,
(Float64, Int32, Int32, Ptr{Uint8}, Int32,
Ptr{Bool}, Ptr{Int32}, Ptr{Int32}),
$value, $mode, $ndigits,
$esc(value), $esc(mode), $esc(ndigits),
_digits, _buflen, _neg, _len, _point)
end
end
Expand Down
39 changes: 21 additions & 18 deletions base/printf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -752,30 +752,33 @@ end

### external printf interface ###

function f_str_f(f)
args, blk = printf_gen(f)
:(($expr(:tuple, args))->($blk))
end

macro f_str(f); f_str_f(f); end

macro printf(f, exps...)
args, blk = printf_gen(f)
if length(args) != length(exps)
error("printf: wrong number of arguments")
macro printf(args...)
local io, fmt
if isa(args[1],String)
io = :(Base.OUTPUT_STREAM)
fmt = args[1]
args = args[2:]
else
io = args[1]
fmt = args[2]
args = args[3:]
end
args = {io,args...}
sym_args, blk = printf_gen(fmt)
if length(sym_args) != length(args)
error("@printf: wrong number of arguments")
end
for i = length(args):-1:1
arg = args[i].args[1]
unshift(blk.args, :($arg = $esc(exps[i])))
var = sym_args[i].args[1]
unshift(blk.args, :($var = $esc(args[i])))
end
blk
end

fprintf(s::IOStream, f::Function, args...) = f(s, args...)
fprintf(s::IOStream, fmt::String, args...) = fprintf(s, eval(Base,f_str_f(fmt)), args...)
printf(f::Union(Function,String), args...) = fprintf(OUTPUT_STREAM, f, args...)
sprintf(f::Union(Function,String), args...) = sprint(fprintf, f, args...)
macro sprintf(args...)
:(sprint(io->@printf(io,$(map(esc,args)...))))
end

export @f_str, @printf, fprintf, printf, sprintf
export @printf, @sprintf
end # module
import Base.Printf.*
4 changes: 2 additions & 2 deletions base/sysimg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,8 @@ export
@v_str, @unexpected, @assert, @r_str, @str, @S_str, @I_str, @E_str,
@B_str, @b_str, @cmd, @time, @elapsed, @windows_only, @unix_only,
@sync, @spawn, @spawnlocal, @spawnat, @everywhere, @parallel,
@gensym, @eval, @task, @f_str, @thunk, @L_str, @vectorize_1arg,
@vectorize_2arg, @printf
@gensym, @eval, @task, @thunk, @L_str, @vectorize_1arg,
@vectorize_2arg, @printf, @sprintf

if false
# simple print definitions for debugging. enable these if something
Expand Down
2 changes: 1 addition & 1 deletion examples/lru_test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ for lru in (
)
for n in nmax
del_all(lru)
printf(" %s, %d items\n", lru, n)
@printf(" %s, %d items\n", lru, n)
print(" Simple eviction: ")
for i in 1:n
str = get_str(i)
Expand Down
6 changes: 3 additions & 3 deletions examples/shootout/binary-trees.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function loop_depths(d, min_depth, max_depth)
for j = 1:niter
c += check(make(i, d)) + check(make(-i, d))
end
printf("%i\t trees of depth %i\t check: %i\n", 2*niter, d, c)
@printf("%i\t trees of depth %i\t check: %i\n", 2*niter, d, c)
d += 2
end
end
Expand All @@ -48,13 +48,13 @@ function binary_trees(N::Int)

# create and check stretch tree
let c = check(make(0, stretch_depth))
printf("stretch tree of depth %i\t check: %i\n", stretch_depth, c)
@printf("stretch tree of depth %i\t check: %i\n", stretch_depth, c)
end

long_lived_tree = make(0, max_depth)

loop_depths(min_depth, min_depth, max_depth)
printf("long lived tree of depth %i\t check: %i\n", max_depth, check(long_lived_tree))
@printf("long lived tree of depth %i\t check: %i\n", max_depth, check(long_lived_tree))
end

if length(ARGS) >= 1
Expand Down
2 changes: 1 addition & 1 deletion examples/shootout/fannkuch.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,4 +70,4 @@ if length(ARGS) >= 1
else
N = 7
end
printf("Pfannkuchen(%i) = %i\n", N, fannkuch(N))
@printf("Pfannkuchen(%i) = %i\n", N, fannkuch(N))
4 changes: 2 additions & 2 deletions examples/shootout/k-nucleotide.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ function print_knucs(a::Array{KNuc, 1})
sum += kn.count
end
for kn in a
printf(f"%s %.3f\n", kn.name, 100.0kn.count/sum)
@printf("%s %.3f\n", kn.name, 100.0kn.count/sum)
end
println()
end
Expand Down Expand Up @@ -82,7 +82,7 @@ function main()
print_knucs(arr1)
print_knucs(arr2)
for s in ["GGT", "GGTA", "GGTATT", "GGTATTTTAATT", "GGTATTTTAATTTATAGT"]
printf(f"%d\t%s\n", count_one(str, s), s)
@printf("%d\t%s\n", count_one(str, s), s)
end
end

Expand Down
4 changes: 2 additions & 2 deletions examples/shootout/nbody.jl
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,11 @@ end

function nbody(N::Int)
init_sun(bodies)
printf("%.9f\n", energy(bodies))
@printf("%.9f\n", energy(bodies))
for i = 1:N
advance(bodies, 0.01)
end
printf("%.9f\n", energy(bodies))
@printf("%.9f\n", energy(bodies))
end

# main
Expand Down
4 changes: 2 additions & 2 deletions examples/shootout/nbody_vec.jl
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,11 @@ end

function nbody(N::Int)
init_sun(bodies)
printf("%.9f\n", energy(bodies))
@printf("%.9f\n", energy(bodies))
for i = 1:N
advance(bodies, 0.01)
end
printf("%.9f\n", energy(bodies))
@printf("%.9f\n", energy(bodies))
end

# main
Expand Down
2 changes: 1 addition & 1 deletion examples/shootout/pidigits.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ function pidigits(N::Int, printOut::Bool)
if mod(i,10) == 0
if printOut
show(ns)
printf("\t:%d\n", i)
@printf("\t:%d\n", i)
end
if i >= N
return ns
Expand Down
2 changes: 1 addition & 1 deletion examples/shootout/regex-dna.jl
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function main()
for m in each_match(Regex(v), seq)
k += 1
end
printf(f"%s %d\n", v, k)
@printf("%s %d\n", v, k)
end

for (u, v) in subs
Expand Down
2 changes: 1 addition & 1 deletion examples/shootout/spectralnorm.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function approximate(N)
end

function spectralnorm(N)
printf("%.09f\n", approximate(N))
@printf("%.09f\n", approximate(N))
end

if length(ARGS) >= 1
Expand Down
2 changes: 1 addition & 1 deletion examples/shootout/timing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ macro timeit(ex,name)
for $i=1:5
$t = min($t, @elapsed $ex)
end
printf("julia, %s: best of 5 took %.1f ms\n", $name, $t*1000)
@printf("julia, %s: best of 5 took %.1f ms\n", $name, $t*1000)
end
end

Expand Down
4 changes: 2 additions & 2 deletions extras/linalg_suitesparse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ type UmfpackLU{Tv<:Union(Float64,Complex128),Ti<:CHMITypes} <: Factorization{Tv}
end

function show(io, f::UmfpackLU)
printf("UMFPACK LU Factorization of a %d-by-%d sparse matrix\n",
@printf("UMFPACK LU Factorization of a %d-by-%d sparse matrix\n",
size(f.mat,1), size(f.mat,2))
println(f.numeric)
_jl_umfpack_report(f)
Expand All @@ -422,7 +422,7 @@ type UmfpackLUTrans{Tv<:Union(Float64,Complex128),Ti<:CHMITypes} <: Factorizatio
end

function show(io, f::UmfpackLUTrans)
printf("UMFPACK LU Factorization of a transposed %d-by-%d sparse matrix\n",
@printf("UMFPACK LU Factorization of a transposed %d-by-%d sparse matrix\n",
size(f.mat,1), size(f.mat,2))
println(f.numeric)
_jl_umfpack_report(f)
Expand Down
2 changes: 1 addition & 1 deletion extras/profile.jl
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,7 @@ function profile_print(tc)
counters = tc[i][2]
for j = 1:length(counters)
if counters[j] != 0
printf("%8d %f % f %s\n", counters[j], convert(Float64, timers[j])*1e-9, (convert(Float64, timers[j]) - convert(Float64, counters[j])*_PROFILE_CALIB)*1e-9, _PROFILE_TAGS[i][j])
@printf("%8d %f % f %s\n", counters[j], convert(Float64, timers[j])*1e-9, (convert(Float64, timers[j]) - convert(Float64, counters[j])*_PROFILE_CALIB)*1e-9, _PROFILE_TAGS[i][j])
end
end
end
Expand Down
4 changes: 2 additions & 2 deletions extras/strpack.jl
Original file line number Diff line number Diff line change
Expand Up @@ -480,11 +480,11 @@ function show_struct_layout(s::Struct, strategy::DataAlign, width, bytesize)
for i in 1:prod(dims)
tstr = string(typ)
tstr = tstr[1:min(sizeof(typ)*bytesize-2, length(tstr))]
str = sprintf("[%s%s]", tstr, "-"^(bytesize*sizeof(typ)-2-length(tstr)))
str = @sprintf("[%s%s]", tstr, "-"^(bytesize*sizeof(typ)-2-length(tstr)))
typsize = sizeof(typ)
while !isempty(str)
if offset % width == 0
printf("0x%04X ", offset)
@printf("0x%04X ", offset)
end
len_prn = min(width - (offset % width), typsize)
nprint = bytesize*len_prn
Expand Down
2 changes: 1 addition & 1 deletion extras/test.jl
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ function dump(io::IOStream, t::TestResult)
println(io, "$(t.operation) with args:")
println(io, "1: $(t.arg1)\n2: $(t.arg2)\n3: $(t.arg3)")
println(io, "Exception: $(t.exception_thrown)")
println(io, sprintf("%0.3f seconds\n", t.elapsed))
println(io, @sprintf("%0.3f seconds\n", t.elapsed))
end

# things to set state
Expand Down
10 changes: 4 additions & 6 deletions test/perf/perf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -133,13 +133,11 @@ end

@unix_only begin
function printfd(n)
f = open("/dev/null","w")
for i = 1:n
# fprintf(f, f"%d %d\n", i, i)
# f"%d %d\n"(f,i,i)
@printf "%d %d\n" f i i
open("/dev/null","w") do io
for i = 1:n
@printf(io,"%d %d\n",i,i+1)
end
end
close(f)
end

printfd(1)
Expand Down

2 comments on commit 04f542d

@timholy
Copy link
Member

@timholy timholy commented on 04f542d Aug 5, 2012

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is very nice!

@StefanKarpinski
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Closes #140.

Please sign in to comment.