Golang
func warp(f func([]int) int) func([]int) int {
return func(list []int) int {
start := time.Now()
s := f(list)
end := time.Now()
fmt.Println(end.Sub(start))
return s
}
}
list := []int{1,2,6,6}
total := warp(sum)(list)
Nodejs
// js休眠函数
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function sum(list) {
let total = 0;
for (const v of list) {
total += v;
}
await sleep(1000);
return total;
}
// 函数装饰器,js目前不支持类、属性装饰器,只能用typescript
function timerDecorator(func) {
return async function() {
console.time();
const result = await func.apply(this, arguments);
console.timeEnd();
return result;
}
}
timerDecorator(sum)([1,2,3]).then((res) => {
console.log(res);
});
Python
def costime(func):
def warp(*args, **kwargs):
start = time.time()
res = func(*args, **kwargs)
end = time.time()
print(end-start)
return res
return warp
@costime
def sum(*args):
C#
1、Attribute特性实现装饰器:
https://blog.csdn.net/weixin_43263355/article/details/110137016
2、abstract抽象类实现装饰器:
https://www.xin3721.com/ArticlecSharp/c11756.html