[Cython] Feature Request: expand list/tuple in 'if (... in ...):' ...

Stefan Behnel stefan_ml at behnel.de
Thu Jan 24 15:49:25 CET 2013


[moving this to cython-users]

Christian Inci, 24.01.2013 15:13:
> Subject: Feature Request: expand list/tuple in 'if (... in ...):' ...
> 
> expand list/tuple in 'if (... in ...):' on compile-time if the list/tuple contains only static values.
> 
> test1: list is expanded manually.
> test2: list is not expanded.
> 
> The output of the testcase is:
> test1: timediff: 0.205533
> test2: timediff: 17.567185
> 
> 
> Testcase:
> 
> from time import time
> 
> cdef tuple INT_TUPLE = (0x66, 0x67, 0x2e,
>                  0x36, 0x3e, 0x26, 0x64,
>                  0x65, 0xf2, 0xf3, 0xf0)
> 
> cpdef test():
>     cdef unsigned int i
>     cdef unsigned short j # 'unsigned char j' won't work for some reason
>     cdef double start_time
>     start_time = time()
>     for i in range(0x50000):
>         for j in range(256):
>             if (j == 0x66 or j == 0x67 or j == 0x2e or j == 0x36 or j == 0x3e or j == 0x26 or j == 0x64 or j == 0x65 or j == 0xf2 or j == 0xf3 or j == 0xf0):
>                 pass
>     print("test1: timediff: {0:f}".format(time()-start_time))
>     start_time = time()
>     for i in range(0x50000):
>         for j in range(256):
>             if (j in INT_TUPLE):
>                 pass
>     print("test2: timediff: {0:f}".format(time()-start_time))

This is not an optimisation as it might render the code incorrect. How can
Cython know that you'll never change INT_TUPLE at runtime?

However, if you use a literal list or tuple in place, this already works,
i.e. the first example is equivalent to

    if j in (0x66, 0x67, 0x2e,
             0x36, 0x3e, 0x26, 0x64,
             0x65, 0xf2, 0xf3, 0xf0):

You actually get a C switch statement for it.

If you prefer keeping the set of integer values at a separate place, this
should work:

    DEF INT_TUPLE = (0x66, 0x67, 0x2e,
                     0x36, 0x3e, 0x26, 0x64,
                     0x65, 0xf2, 0xf3, 0xf0)

(mind the upper case "DEF").

Stefan


More information about the cython-devel mailing list