Boosting performance with Cython

 
 

Even with my old pc (AMD Athlon II, 3GB ram), I seldom run into performance issues when running vectorized code. But unfortunately there are plenty of cases where that can not be easily vectorized, for example the drawdown function. My implementation of such was extremely slow, so I decided to use it as a test case for speeding things up. I'll be using the SPY timeseries with ~5k samples as test data. Here comes the original version of my drawdown function (as it is now implemented in the TradingWithPython library)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def drawdown(pnl):
    """
    calculate max drawdown and duration
 
    Returns:
        drawdown : vector of drawdwon values
        duration : vector of drawdown duration
    """
    cumret = pnl
 
    highwatermark = [0]
 
    idx = pnl.index
    drawdown = pd.Series(index = idx)
    drawdowndur = pd.Series(index = idx)
 
    for t in range(1, len(idx)) :
        highwatermark.append(max(highwatermark[t-1], cumret[t]))
        drawdown[t]= (highwatermark[t]-cumret[t])
        drawdowndur[t]= (0 if drawdown[t] == 0 else drawdowndur[t-1]+1)
 
    return drawdown, drawdowndur
 
%timeit drawdown(spy)
1 loops, best of 3: 1.21 s per loop

Hmm 1.2 seconds is not too speedy for such a simple function. There are some things here that could be a great drag to performance, such as a list *highwatermark* that is being appended on each loop iteration. Accessing Series by their index should also involve some processing that is not strictly necesarry. Let's take a look at what happens when this function is rewritten to work with numpy data

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def dd(s):
#    ''' simple drawdown function '''
     
    highwatermark = np.zeros(len(s))
    drawdown = np.zeros(len(s))
    drawdowndur = np.zeros(len(s))
 
  
    for t in range(1,len(s)):
        highwatermark[t] = max(highwatermark[t-1], s[t])
        drawdown[t] = (highwatermark[t]-s[t])
        drawdowndur[t]= (0 if drawdown[t] == 0 else drawdowndur[t-1]+1)
        
      
    return drawdown , drawdowndur
 
%timeit dd(spy.values)
10 loops, best of 3: 27.9 ms per loop

Well, this is much faster than the original function, approximately 40x speed increase. Still there is much room for improvement by moving to compiled code with cython Now I rewrite the dd function from above, but using optimisation tips that I've found on the cython tutorial .

用cython提升python的性能的更多相关文章

  1. 七个可以提升python程序性能的好习惯,你知道吗?

    掌握一些技巧,可尽量提高Python程序性能,也可以避免不必要的资源浪费.今天就为大家带来七个可以提升python程序性能的好习惯,赶快来学习吧:. 1.使用局部变量 尽量使用局部变量代替全局变量:便 ...

  2. 7个提升Python程序性能的好习惯

    原文作者:爱coding,会编程的核电工程师. 个人博客地址:zhihu.com/people/zhong-yun-75-63 掌握一些技巧,可尽量提高Python程序性能,也可以避免不必要的资源浪费 ...

  3. 【python 应用之四】提升 Python 运行性能的 7 个习惯

    大家都知道艺赛旗的 RPA 依赖于 python 语言.因此我们可以掌握一些技巧,可尽量提高 Python 程序性能,也可以避免不必要的资源浪费.1.使用局部变量 尽量使用局部变量代替全局变量:便于维 ...

  4. [转] Python 代码性能优化技巧

    选择了脚本语言就要忍受其速度,这句话在某种程度上说明了 python 作为脚本的一个不足之处,那就是执行效率和性能不够理想,特别是在 performance 较差的机器上,因此有必要进行一定的代码优化 ...

  5. Python代码性能优化技巧

    摘要:代码优化能够让程序运行更快,可以提高程序的执行效率等,对于一名软件开发人员来说,如何优化代码,从哪里入手进行优化?这些都是他们十分关心的问题.本文着重讲了如何优化Python代码,看完一定会让你 ...

  6. Python 代码性能优化技巧(转)

    原文:Python 代码性能优化技巧 Python 代码优化常见技巧 代码优化能够让程序运行更快,它是在不改变程序运行结果的情况下使得程序的运行效率更高,根据 80/20 原则,实现程序的重构.优化. ...

  7. Python 代码性能优化技巧

    选择了脚本语言就要忍受其速度,这句话在某种程度上说明了 python 作为脚本的一个不足之处,那就是执行效率和性能不够理想,特别是在 performance 较差的机器上,因此有必要进行一定的代码优化 ...

  8. 用Cython加速Python程序以及包装C程序简单测试

    用Cython加速Python程序 我没有拼错,就是Cython,C+Python=Cython! 我们来看看Cython的威力,先运行下边的程序: import time def fib(n): i ...

  9. psutil 是因为该包能提升 memory_profiler 的性能

    python 性能分析入门指南 一点号数据玩家昨天 限时干货下载:添加微信公众号"数据玩家「fbigdata」" 回复[7]免费获取[完整数据分析资料!(包括SPSS.SAS.SQ ...

随机推荐

  1. vsftpd增加ssl安全验证

    查看vsftpd是否支持ssl ldd `which vsftpd`|grep ssl 输出 libssl.so.6 => /lib64/libssl.so.6 (0x00002ba684304 ...

  2. soap request by afnetworking2.X/3.X

    for 2.X 参考 http://jiapumin.iteye.com/blog/2109378 AFHTTPRequestOperationManager *manager = [AFHTTPRe ...

  3. ios计算内容的高度 (含7.0前及以后的版本的用法)

    + (CGFloat)heightForContent:(MyMsgTextModel *)content withWidth:(CGFloat)width { CGSize contentSize; ...

  4. UINavigation Bar中使用UIcollectionView,在UIcollectionView的顶端和低端出现空白的问题

    在含有UINavigation Bar的视图中,使用UIcollectionView,会在UIcollectionView的顶端和低端出现空白,需要添加下面 一句代码,空白即可消失   //如果不加这 ...

  5. [转]Android SHA1与Package获取方式

    转自高德地图LBS Android SHA1与Package获取方式 获取应用包名 打开Android 应用工程的 AndroidManifest.xml配置文件,package 属性所对应的内容为应 ...

  6. PowerShell 常用命令

    下载文件 http://powershell.com/cs/blogs/tips/archive/2012/10/11/downloading-files-from-internet.aspx Pow ...

  7. C# 遍历类的属性并取出值

    最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精    今天有点胡思乱想,想遍历MVC Model的属性并 ...

  8. Leetcode: All O`one Data Structure

    Implement a data structure supporting the following operations: Inc(Key) - Inserts a new key with va ...

  9. JS实时数据运算

    应朋友需要制作的一个小页面 <script type="text/javascript"> function cal(ida,idb,idc,idd) { var nu ...

  10. BJFU 1015

    描述 数字具有神奇的魔力,神奇到ben想把所有数字全部保存起来.于是他设想了如下的保存方法.假设有一张无限大的纸板,将所有自然数(不包括0)按如下顺序排列书写在纸板上保存:1 2 6 7  15  1 ...