In my plugin library, I define the following to help running a function n times in order to have an estimation of the time it takes to execute
It's meant to be used this way
echo lh#time#bench_n(10000, function('Function1'), the, list, of, parameters)[1] / 10000
lh#time#bench_n()
returns a list of two elements: the 10000 results of the 10000 function calls (in order to check the function, and the benchmark, execute correctly -- when the parameters are lists, there are some mishaps sometimes and we need to control we are benchmarking something meaningful), and the total execution time.
The becnhmarking functions are defined this way:
" # Bench
{{{2
" Function: lh#time#bench(F) {{{3
if exists('*reltimefloat')
function! lh#time#bench(F, ...) abort
let t0 = reltime()
let res = call(a:F, a:000)
let t = reltime()
return [res, reltimefloat(reltime(t0, t))]
endfunction
elseif exists('*reltime')
function! lh#time#bench(F, ...) abort
let t0 = reltime()
let res = call(a:F, a:000)
let t = reltime()
return [res, eval(reltimestr(reltime(t0, t)))]
endfunction
else
function! lh#time#bench(F, ...) abort
let res = call(a:F, a:000)
return [res, 0]
endfunction
endif
" Function: lh#time#bench_n(n, F, ...) {{{3
function! lh#time#bench_n(n, F, ...) abort
let tot = 0
for i in range(1, a:n)
let [res, b] = call('lh#time#bench', [a:F] + deepcopy(a:000))
let tot += b
endfor
return [res, tot]
endfunction