python branch-prediction-problem.py

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python branch-prediction-problem.py相关的知识,希望对你有一定的参考价值。

#!/usr/bin/env python
# coding: utf-8
# from pprint import pprint as print

# https://stackoverflow.com/questions/11227809/why-is-it-faster-to-process-a-sorted-array-than-an-unsorted-array

# https://www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods

from __future__ import print_function
import random
from functools import reduce
import time                                                


N = int(1e6)


def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        # print(method.__name__, str(te), str(ts))
        print ('%r %5.5f msec'  %(method.__name__, 1e3*(te-ts)))
        return result

    return timed

def data():
    return map(lambda x: random.randint(-N, N), range(N))


@timeit
def summarize(_):
    pos, neg = 0, 0
    pos = sum(map(lambda x: x if x > 0 else 0, _))
    neg = sum(map(lambda x: x if x < 0 else 0, _))
    return neg, pos


@timeit
def summarize_2(_):
    pos, neg = 0, 0
    for e in _:
        if e < 0:
            neg += e 
        else:
            pos += e
    
    return neg, pos
def pos_reducer(x, y):
    if (x > 0 and y > 0):
        return x + y
    if (x > 0 and y <= 0):
        return x
    if (y > 0 and x <= 0):
        return y
    return 0

def neg_reducer(x, y):
    if (x < 0 and y < 0):
        return x + y
    if (x < 0 and y >= 0):
        return x
    if (y < 0 and x >= 0):
        return y
    return 0

@timeit
def summarize_(_):
    pos, neg = 0, 0
    pos = reduce(pos_reducer, _)
    neg = reduce(neg_reducer, _)
    return neg, pos



def main():
    arr = list(data())
    print(summarize(arr))
    print(summarize_(arr))
    print(summarize_2(arr))

    # arr.sort()
    print(summarize(arr))
    print(summarize_(arr))
    print(summarize_2(list(sorted(arr))))
    # print(summarize_(arr[:]))

if __name__ == '__main__':
    main()

以上是关于python branch-prediction-problem.py的主要内容,如果未能解决你的问题,请参考以下文章

Python代写,Python作业代写,代写Python,代做Python

Python开发

Python,python,python

Python 介绍

Python学习之认识python

python初识