Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7996395
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T14:41:57+00:00 2026-06-04T14:41:57+00:00

I am trying to optimize my code with Cython. It is doing a a

  • 0

I am trying to optimize my code with Cython. It is doing a a power spectrum, not using FFT, because this is what we were told to do in class. I’ve tried to write to code in Cython, but do not see any difference.
Here is my code

#! /usr/bin/env python
# -*- coding: utf8 -*-

from __future__ import division
cimport numpy as np
import numpy as np
cimport cython

@cython.boundscheck(False)
def power_spectrum(time, data, double f_min, double f_max, double df,w=1 ):

    cdef double com,f
    cdef double s,c,sc,cc,ss
    cdef np.ndarray[double, ndim=1] power
    cdef np.ndarray[double, ndim=1] freq

    alfa, beta = [],[] 
    m = np.mean(data)
    data -= m       

    freq = np.arange( f_min,f_max,df )
    for f in freq:
            sft = np.sin(2*np.pi*f*time)
            cft = np.cos(2*np.pi*f*time)
            s   = np.sum( w*data*sft )
            c   = np.sum( w*data*cft )
            ss  = np.sum( w*sft**2  )
            cc  = np.sum( w*cft**2  )
            sc  = np.sum( w*sft*cft )

            alfa.append( ( s*cc-c*sc )/( ss*cc-sc**2 ))
            beta.append( ( c*ss-s*sc )/( ss*cc-sc**2 ))
            com = -(f-f_min)/(f_min-f_max)*100
            print "%0.3f%% complete" %com

    power = np.array(alfa)**2 + np.array(beta)**2
    return freq,power,alfa,beta

The time and data is loaded via numpy.loadtxt and sent to this function.
When I do

cython -a power_spectrum.pyx

the .html file is very yellow, so not very efficient. Especially the entire for-loop and the calulation of power and returning everything.

I have tried to read the official guide to Cython, but as I have never coded in C it is somewhat hard to understand.

All help is very preciated 🙂

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T14:41:58+00:00Added an answer on June 4, 2026 at 2:41 pm

    Cython can read numpy arrays according to this but it won’t magically compile stuff like np.sum – you are still just calling the numpy methods.

    What you need to do is re-write your inner loop in pure cython which can then compile it for you. So you will need to re-implement np.sum, np.sin etc. Pre-allocating aplfa and beta is a good idea so you don’t use append and try to cdef as many variables as possible.

    EDIT

    Here is an complete example showing the inner loop completely C compiled (no yellow). I’ve no idea whether the code is correct but it should be a good starting point! In particular note use of cdef everywhere, turning on cdivision and import of sin and cos from the standard library.

    from __future__ import division
    cimport numpy as np
    import numpy as np
    cimport cython
    from math import pi
    
    cdef extern from "math.h":
        double cos(double theta)
        double sin(double theta)
    
    @cython.boundscheck(False)
    @cython.cdivision(True)
    def power_spectrum(np.ndarray[double, ndim=1] time, np.ndarray[double, ndim=1] data, double f_min, double f_max, double df, double w=1 ):
    
        cdef double com,f
        cdef double s,c,sc,cc,ss,t,d
        cdef double twopi = 6.283185307179586
        cdef np.ndarray[double, ndim=1] power
        cdef np.ndarray[double, ndim=1] freq = np.arange( f_min,f_max,df )
        cdef int n = len(freq)
        cdef np.ndarray[double, ndim=1] alfa = np.zeros(n)
        cdef np.ndarray[double, ndim=1] beta = np.zeros(n)
        cdef int ndata = len(data)
        cdef int i, j
    
        m = np.mean(data)
        data -= m       
    
        for i in range(ndata):
            f = freq[i]
    
            s = 0.0
            c = 0.0
            ss = 0.0
            cc = 0.0
            sc = 0.0
            for j in range(n):
                t = time[j]
                d = data[j]
                sf = sin(twopi*f*t)
                cf = cos(twopi*f*t)
                s += w*d*sf
                c += w*d*cf
                ss += w*sf**2
                cc += w*cf**2
                sc += w*sf*cf
    
            alfa[i] = ( s*cc-c*sc )/( ss*cc-sc**2 )
            beta[i] = ( c*ss-s*sc )/( ss*cc-sc**2 )
    
        power = np.array(alfa)**2 + np.array(beta)**2
        return freq,power,alfa,beta
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

While reading a post on StackOverflow (http://stackoverflow.com/questions/1502081/im-trying-to-optimize-this-c-code-using-4-way-loop-unrolling), which is now marked as closed, I
I'm trying to optimize my C++ code. I've searched the internet on using dynamically
I'm trying to optimize the performance of my code, but I'm not familiar with
I`m having trouble trying to optimize this query with OVER (PARTITION BY ...) because
I needed some help in trying to optimize this code portion ... Basically here's
I'm trying to optimize the following. The code bellow does this : If a
i'm trying to optimize this code: foreach (string id in ids) { MyClass x
I'm trying to condense/improve/optimize this code cleaned = stringwithslashes cleaned = cleaned.replace(\\n, \n) cleaned
I have been trying to optimize this code: def spectra(mE, a): pdf = lambda
I am trying to optimize a query that does something like this: SELECT ...

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.