# coding = utf-8
from functools import wraps import time def func1(func): @wraps(func) def call_func(*args, **kwargs): start2 = time.time() func(*args, **kwargs) end2 = time.time() cost = end2 - start2 print "{} cost {}ms".format(func.__name__, cost) return call_func @func1 def test_cmp(alist): for i in range(1000000): f2 = sorted(alist, cmp=lambda x, y: cmp(x.get(1), y.get(1)), reverse=True) print alist @func1 def test_key(alist): for i in range(1000000): f2 = sorted(alist, key=lambda x: x.get(1), reverse=True) print alist if __name__ == '__main__': aa = [{1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}, {1: 9}] test_cmp(aa) test_key(aa)
# 执行结果:
[{1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}, {1: 9}]
test_cmp cost 5.07299995422ms
[{1: 5, 3: 4}, {1: 3, 6: 3}, {1: 1, 2: 4, 5: 6}, {1: 9}]
test_key cost 2.94199991226ms