Skip to content

Instantly share code, notes, and snippets.

@dander
Forked from greggirwin/profile.red
Created November 14, 2017 06:21
Show Gist options
  • Save dander/7128a8976ffc9ab7b0fe4a654157c9e5 to your computer and use it in GitHub Desktop.
Save dander/7128a8976ffc9ab7b0fe4a654157c9e5 to your computer and use it in GitHub Desktop.
Basic profiling for Red code comparisons
Red []
e.g.: :comment
delta-time: function [
"Return the time it takes to evaluate a block"
block [block! word! function!] "Block to evaluate"
/count ct "Eval the block this many times, rather than once"
][
ct: any [ct 1]
t: now/time/precise
loop ct [do block]
now/time/precise - t
]
profile: function [
"Profile code, returning [time memory source] results"
blocks [block!] "Block of code values (block, word, or function) to profile"
/count ct "Eval code this many times, rather than once"
/show "Display results, instead of returning them as a block"
][
ct: any [ct 1] ; set number of evaluations
baseline: delta-time/count [] ct
res: collect [
foreach blk blocks [
stats-1: stats ; get current stats before evaluation
n: subtract delta-time/count :blk ct baseline
keep/only reduce [
round/to n .001
round/to n / ct .001
stats - stats-1
either block? :blk [copy blk][:blk]
]
]
]
sort res ; sort by time
either show [
print ["Count:" ct]
template: [pad (time) 12 #"|" pad (time-per) 12 #"|" pad (memory) 11 #"|" (mold :code)]
insert/only res ["Time" "Time (Per)" "Memory" Code] ; last column is molded, so not a string here
foreach blk res [
set [time time-per memory code] blk
print compose template
]
][
insert/only res compose [count: (ct) fields: [Time Time-Per Memory Code]]
new-line/all res on ; Return formatted results
]
]
e.g. [
profile [[wait 1] [wait .25] [wait .5]]
profile/count [[100 / 1 * (100 / 1)] [100.0 / 1.0 ** 2] [100% / 1%]] 1000000
one: [1 + 1]
two: [2 + 2]
profile [one two]
profile/show [[wait 1] [wait .25] [wait .5]]
profile/show/count [[100 / 1 * (100 / 1)] [100.0 / 1.0 ** 2] [100% / 1%]] 1000000
profile/show [one two]
f1: does [wait .25]
f2: does [wait .5]
profile/show/count reduce [:f1 :f2] 2
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment