The document summarizes a presentation on Cython, a programming language that allows writing Python extensions and integrating Python with C/C++ code. Cython code can be compiled into C/C++ extensions that speed up Python code by allowing static type declarations. The presentation covers Cython features like static typing, C pointers and strings, exception handling, and defining extension types. It provides examples of Cython code and compiling Cython to C/C++ extensions using various methods.
After the end of lesson you will be able to learn Python basics-What Python is? Its releases. Where we can use Python? Python Features. Tokens, comments variables etc... In out next PPT you will learn how to input and get output in Python
After the end of lesson you will be able to learn Python basics-What Python is? Its releases. Where we can use Python? Python Features. Tokens, comments variables etc... In out next PPT you will learn how to input and get output in Python
** Python Certification Training: https://www.edureka.co/python **
This Edureka tutorial on "Python Tutorial for Beginners" (Python Blog Series: https://goo.gl/nKQJHQ) covers all the basics of Python. It includes python programming examples, so try it yourself and mention in the comments section if you have any doubts. Following are the topics included in this PPT:
Introduction to Python
Reasons to choose Python
Installing and running Python
Development Environments
Basics of Python Programming
Starting with code
Python Operators
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Looping in Python
Python Functions
Python Arrays
Classes and Objects (OOP)
Conclusion
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The tutorial will give you a brief introduction to Generators in Python. Next, you will learn the advantages of using generators in Python. Further, you will know the utility of the next() function.
After that, we will have hands-on demonstrations for Generators in Python.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.
When developing software with Python, a basic approach is to install Python on your machine, install all your required libraries via the terminal and write all of the source code. This works fine for simple Python scripting projects.
Introduction about Python by JanBask Training, we are offering Online Pyton Training. You should visit: http://www.janbasktraining.com/python/ for Pyton Training.
YouTube Link: https://youtu.be/QswQA1lRIQY
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Collections In Python' will cover the concepts of Collection data type in python along with the collections module and specialized collection data structures like counter, chainmap, deque etc. Following are the topics discussed:
What Are Collections In Python?
What Is A Collection Module In Python?
Specialized Collection Data Structures
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Introduction to python -easiest way to understand python for beginners
What is Python…?
Differences between programming and scripting language
Programming Paradigms
History of Python
Scope of Python
Why do people use Python?
Installing Python
Introduction to Python IDLE | IDLE Tutorial | EdurekaEdureka!
YouTube Link: https://youtu.be/riL_xn6BKD8
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Python IDLE' will train you to use IDLE which is an IDE that comes as a default implementation when you install python.
Below are the topics covered in this PPT:
What is IDLE?
IDLE Installation
Working with IDLE
Configuration
Basic Examples
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Basics of Iterators and Generators,Uses of iterators and generators in python. advantage of iterators and generators. difference between generators and iterators.
This presentation is about using Boost.Python library to create modules with С++.
Presentation by Andriy Ohorodnyk (Lead Software Engineer, GlobalLogic, Lviv), delivered GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
** Python Certification Training: https://www.edureka.co/python **
This Edureka tutorial on "Python Tutorial for Beginners" (Python Blog Series: https://goo.gl/nKQJHQ) covers all the basics of Python. It includes python programming examples, so try it yourself and mention in the comments section if you have any doubts. Following are the topics included in this PPT:
Introduction to Python
Reasons to choose Python
Installing and running Python
Development Environments
Basics of Python Programming
Starting with code
Python Operators
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Looping in Python
Python Functions
Python Arrays
Classes and Objects (OOP)
Conclusion
Follow us to never miss an update in the future.
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
The tutorial will give you a brief introduction to Generators in Python. Next, you will learn the advantages of using generators in Python. Further, you will know the utility of the next() function.
After that, we will have hands-on demonstrations for Generators in Python.
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed.
When developing software with Python, a basic approach is to install Python on your machine, install all your required libraries via the terminal and write all of the source code. This works fine for simple Python scripting projects.
Introduction about Python by JanBask Training, we are offering Online Pyton Training. You should visit: http://www.janbasktraining.com/python/ for Pyton Training.
YouTube Link: https://youtu.be/QswQA1lRIQY
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Collections In Python' will cover the concepts of Collection data type in python along with the collections module and specialized collection data structures like counter, chainmap, deque etc. Following are the topics discussed:
What Are Collections In Python?
What Is A Collection Module In Python?
Specialized Collection Data Structures
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Introduction to python -easiest way to understand python for beginners
What is Python…?
Differences between programming and scripting language
Programming Paradigms
History of Python
Scope of Python
Why do people use Python?
Installing Python
Introduction to Python IDLE | IDLE Tutorial | EdurekaEdureka!
YouTube Link: https://youtu.be/riL_xn6BKD8
** Python Certification Training: https://www.edureka.co/python **
This Edureka PPT on 'Python IDLE' will train you to use IDLE which is an IDE that comes as a default implementation when you install python.
Below are the topics covered in this PPT:
What is IDLE?
IDLE Installation
Working with IDLE
Configuration
Basic Examples
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Castbox: https://castbox.fm/networks/505?country=in
Basics of Iterators and Generators,Uses of iterators and generators in python. advantage of iterators and generators. difference between generators and iterators.
This presentation is about using Boost.Python library to create modules with С++.
Presentation by Andriy Ohorodnyk (Lead Software Engineer, GlobalLogic, Lviv), delivered GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
Talk at PyCon2022 over building binary packages for Python. Covers an overview and an in-depth look into pybind11 for binding, scikit-build for creating the build, and build & cibuildwheel for making the binaries that can be distributed on PyPI.
20145-5SumII_CSC407_assign1.htmlCSC 407 Computer Systems II.docxeugeniadean34240
20145-5SumII_CSC407_assign1.html
CSC 407: Computer Systems II: 2015 Summer II, Assignment #1
Last Modified 2015 July 21Purpose:
To go over issues related to how the compiler and the linker
serve you, the programmer.
Computing
Please ssh into ctilinux1.cstcis.cti.depaul.edu, or use your own Linux machine.
Compiler optimization (45 Points)
Consider the following program.
/* q1.c
*/
#include <stdlib.h>
#include <stdio.h>
#define unsigned int uint
#define LENGTH ((uint) 512*64)
int initializeArray (uint len,
int* intArray
)
{
uint i;
for (i = 0; i < len; i++)
intArray[i] = (rand() % 64);
}
uint countAdjacent (int maxIndex,
int* intArray,
int direction
)
{
uint i;
uint sum = 0;
for (i = 0; i < maxIndex; i++)
if ( ( intArray[i] == (intArray[i+1] + direction) ) &&
( intArray[i] == (intArray[i+2] + 2*direction) )
)
sum++;
return(sum);
}
uint funkyFunction (uint len,
int* intArray
)
{
uint i;
uint sum = 0;
for (i = 0; i < len-1; i++)
if ( (i % 8) == 0x3 )
sum += 7*countAdjacent(len-2,intArray,+1);
else
sum += 17*countAdjacent(len-2,intArray,-1);
return(sum);
}
int main ()
{
int* intArray = (int*)calloc(LENGTH,sizeof(int));
initializeArray(LENGTH,intArray);
printf("funkyFunction() == %d\n",funkyFunction(LENGTH,intArray));
free(intArray);
return(EXIT_SUCCESS);
}
(8 Points) Compile it for profiling but with no extra optimization with:
$ gcc -o q1None -pg q1.c # Compiles q1.c to write q1None to make profile info
$ ./q1None # Runs q1None
$ gprof q1None # Gives profile info on q1None
Be sure to scroll all the way to the top of gprof output!
What are the number of self seconds taken by:
FunctionSelf secondsinitializeBigArray()__________countAdjaceent()__________funkyFunction()__________
(8 Points)
How did it do the operation (i % 8) == 0x3?
Was it done as a modulus (the same as an expensive division, but returns the remainder instead of the quotient) or something else?
Show the assembly language for this C code
using gdb to dissassemble
funkyFunction() of q1None.
Hint: do:
$ gdb q1None
. . .
(gdb) disass funkyFunction
Dump of assembler code for function funkyFunction:
. . .
and then look for the code that sets up the calls to countAdjacent().
The (i % 8) == 0x3 test is done before either countAdjacent() call.
(8 Points) Compile it for profiling but with optimization with:
$ gcc -o q1Compiler -O1 -pg q1.c # Compiles q1.c to write q1Compiler to make profile info
$ ./q1Compiler # Runs q1Compiler
$ gprof q1Compiler # Gives profile info on q1Compiler
What are the number of self seconds taken by:
FunctionSelf secondsinitializeBigArray()__________countAdjacent()__________funkyFunction()__________(8 Points) Use gdb to dissassemble countAdjacent() of both q1None and q1.
"TCP Input Text" implements the Google SOAP Search API and Bing API v2 to extract TCP Ports and Fully Qualified Domain Names (FQDN) from Google Search Results into a .csv file and individual shell scripts for maltego, nmap and nc aka netcat to provide assurance of a listening TCP service since the time that has past of the last crawl performed by the GoogleBot and BingBot
Kosmik is the best institute for Python training in Hyderabad Kukatpally/KPHB. kosmik provides lab facilities with complete real-time training with live sessions
call now: +91-8712186898, +91-8179496603, +91-6309565721
A Study of Variable-Role-based Feature Enrichment in Neural Models of CodeAftab Hussain
Understanding variable roles in code has been found to be helpful by students
in learning programming -- could variable roles help deep neural models in
performing coding tasks? We do an exploratory study.
- These are slides of the talk given at InteNSE'23: The 1st International Workshop on Interpretability and Robustness in Neural Software Engineering, co-located with the 45th International Conference on Software Engineering, ICSE 2023, Melbourne Australia
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Globus
Large Language Models (LLMs) are currently the center of attention in the tech world, particularly for their potential to advance research. In this presentation, we'll explore a straightforward and effective method for quickly initiating inference runs on supercomputers using the vLLM tool with Globus Compute, specifically on the Polaris system at ALCF. We'll begin by briefly discussing the popularity and applications of LLMs in various fields. Following this, we will introduce the vLLM tool, and explain how it integrates with Globus Compute to efficiently manage LLM operations on Polaris. Attendees will learn the practical aspects of setting up and remotely triggering LLMs from local machines, focusing on ease of use and efficiency. This talk is ideal for researchers and practitioners looking to leverage the power of LLMs in their work, offering a clear guide to harnessing supercomputing resources for quick and effective LLM inference.
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns
Unlocking Business Potential: Tailored Technology Solutions by Prosigns
Discover how Prosigns, a leading technology solutions provider, partners with businesses to drive innovation and success. Our presentation showcases our comprehensive range of services, including custom software development, web and mobile app development, AI & ML solutions, blockchain integration, DevOps services, and Microsoft Dynamics 365 support.
Custom Software Development: Prosigns specializes in creating bespoke software solutions that cater to your unique business needs. Our team of experts works closely with you to understand your requirements and deliver tailor-made software that enhances efficiency and drives growth.
Web and Mobile App Development: From responsive websites to intuitive mobile applications, Prosigns develops cutting-edge solutions that engage users and deliver seamless experiences across devices.
AI & ML Solutions: Harnessing the power of Artificial Intelligence and Machine Learning, Prosigns provides smart solutions that automate processes, provide valuable insights, and drive informed decision-making.
Blockchain Integration: Prosigns offers comprehensive blockchain solutions, including development, integration, and consulting services, enabling businesses to leverage blockchain technology for enhanced security, transparency, and efficiency.
DevOps Services: Prosigns' DevOps services streamline development and operations processes, ensuring faster and more reliable software delivery through automation and continuous integration.
Microsoft Dynamics 365 Support: Prosigns provides comprehensive support and maintenance services for Microsoft Dynamics 365, ensuring your system is always up-to-date, secure, and running smoothly.
Learn how our collaborative approach and dedication to excellence help businesses achieve their goals and stay ahead in today's digital landscape. From concept to deployment, Prosigns is your trusted partner for transforming ideas into reality and unlocking the full potential of your business.
Join us on a journey of innovation and growth. Let's partner for success with Prosigns.
Enterprise Resource Planning System includes various modules that reduce any business's workload. Additionally, it organizes the workflows, which drives towards enhancing productivity. Here are a detailed explanation of the ERP modules. Going through the points will help you understand how the software is changing the work dynamics.
To know more details here: https://blogs.nyggs.com/nyggs/enterprise-resource-planning-erp-system-modules/
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
Atelier - Innover avec l’IA Générative et les graphes de connaissancesNeo4j
Atelier - Innover avec l’IA Générative et les graphes de connaissances
Allez au-delà du battage médiatique autour de l’IA et découvrez des techniques pratiques pour utiliser l’IA de manière responsable à travers les données de votre organisation. Explorez comment utiliser les graphes de connaissances pour augmenter la précision, la transparence et la capacité d’explication dans les systèmes d’IA générative. Vous partirez avec une expérience pratique combinant les relations entre les données et les LLM pour apporter du contexte spécifique à votre domaine et améliorer votre raisonnement.
Amenez votre ordinateur portable et nous vous guiderons sur la mise en place de votre propre pile d’IA générative, en vous fournissant des exemples pratiques et codés pour démarrer en quelques minutes.
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Globus
The U.S. Geological Survey (USGS) has made substantial investments in meeting evolving scientific, technical, and policy driven demands on storing, managing, and delivering data. As these demands continue to grow in complexity and scale, the USGS must continue to explore innovative solutions to improve its management, curation, sharing, delivering, and preservation approaches for large-scale research data. Supporting these needs, the USGS has partnered with the University of Chicago-Globus to research and develop advanced repository components and workflows leveraging its current investment in Globus. The primary outcome of this partnership includes the development of a prototype enterprise repository, driven by USGS Data Release requirements, through exploration and implementation of the entire suite of the Globus platform offerings, including Globus Flow, Globus Auth, Globus Transfer, and Globus Search. This presentation will provide insights into this research partnership, introduce the unique requirements and challenges being addressed and provide relevant project progress.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
Software Engineering, Software Consulting, Tech Lead, Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Transaction, Spring MVC, OpenShift Cloud Platform, Kafka, REST, SOAP, LLD & HLD.
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Top 7 Unique WhatsApp API Benefits | Saudi ArabiaYara Milbes
Discover the transformative power of the WhatsApp API in our latest SlideShare presentation, "Top 7 Unique WhatsApp API Benefits." In today's fast-paced digital era, effective communication is crucial for both personal and professional success. Whether you're a small business looking to enhance customer interactions or an individual seeking seamless communication with loved ones, the WhatsApp API offers robust capabilities that can significantly elevate your experience.
In this presentation, we delve into the top 7 distinctive benefits of the WhatsApp API, provided by the leading WhatsApp API service provider in Saudi Arabia. Learn how to streamline customer support, automate notifications, leverage rich media messaging, run scalable marketing campaigns, integrate secure payments, synchronize with CRM systems, and ensure enhanced security and privacy.
1. March 2016 NoVa Python Meetup
Brief Introduction to Cython
Aleksandar Jelenak
2. March 2016 NoVa Python Meetup
What is Cython?
A programming language with Python-like syntax and C/C++-like static typing.
Optimizing static compiler that translates Python/Cython to C/C++ code.
2
3. March 2016 NoVa Python Meetup
● Speed up critical parts of Python code using static typing (measure performance
first!)
● Accelerate data exchange between array-like structures (multidimensional
NumPy arrays, str, bytes. bytearray, array.array, ctypes)
● Integrate Python with existing C/C++ applications and libraries
3
How can Cython help?
4. March 2016 NoVa Python Meetup
Further Information
4
Book: Cython: A Guide for Python Programmers, Kurt Smith
Home page: http://cython.org
Documentation: http://docs.cython.org
FAQ: https://github.com/cython/cython/wiki/FAQ
User mailing list: https://groups.google.com/forum/#!forum/cython-users
5. March 2016 NoVa Python Meetup
Installation
● C/C++ compiler (Mac OS X: Xcode; Windows: Visual Studio)
● Many Python distributions
○ Enthought’s Canopy
○ Continuum’s Anaconda Python
○ Python(x,y)
● Package management systems
○ Linux: apt-get, yum
○ OS X: MacPorts, Homebrew
● For the latest version
○ pip install cython
○ python setup.py install
5
6. March 2016 NoVa Python Meetup
● Implementation files (.pyx)
○ Cython source code
● Definition files (.pxd)
○ C-level constructs definitions (similar to C/C++ header files)
● Include files (.pxi)
○ Specific information for abstracting away any differences in order to produce consistent code
interface
6
Code Organization
7. March 2016 NoVa Python Meetup
Example: Fibonacci Numbers
Python: fib.py
def fib(n):
a = 0
b = 1
for i in range(n):
a, b = a + b, a
return a
Cython: cyfib.pyx
def fib(int n):
cdef int i
cdef double a = 0.0
cdef double b = 1.0
for i in range(n):
a, b = a + b, a
return a
7
8. March 2016 NoVa Python Meetup
● Python’s build tools
● Automatically at import
● From Jupyter (IPython) session
● Integrated into make or Cmake build systems
What happens:
● Cython compiler transforms Python/Cython source code into platform-
independent, optimized C or C++ code.
● C/C++ compiler generates platform-specific shared library from the C/C++ code.
● Produced shared library file is called extension module and can be imported as
any other Python module.
8
How to Compile Cython Code
9. March 2016 NoVa Python Meetup
● Command-line tool for translating Python/Cython code to C/C++ code
● Useful options:
○ -a, --annotate Produce a colorized HTML version of the source
○ -o, --output-file <filename> Specify name of generated C file
○ -t, --timestamps Only compile newer source files
○ -f, --force Compile all source files (overrides implied -t)
○ --line-directives Produce #line directives pointing to the .pyx source
○ --cplus Output a C++ rather than C file
○ -2 Compile based on Python-2 syntax and code semantics
○ -3 Compile based on Python-3 syntax and code semantics
9
The cython Command
10. March 2016 NoVa Python Meetup
Annotation file: cython -a fib.py
● Beside C/C++ code output, produce also an
HTML file with code annotations of the
Python/Cython source code.
● Yellow lines indicate the number of Python
C API calls.
● Less yellow generally indicates better
performance.
● Clicking on each line with “+” displays the
generated C/C++ code.
● The for loop lines have the largest amount
of Python C API calls because the types of
the n, a, and b variables are not specified.
10
11. March 2016 NoVa Python Meetup
Annotation file: cython -a fib.pyx
● Beside C/C++ code output, produce also an
HTML file with code annotations of the
Python/Cython source code.
● Yellow lines indicate the number of Python
C API calls.
● Less yellow generally indicates better
performance.
● Clicking on each line with “+” displays the
generated C/C++ code.
● Because of static typing of the n, a, and b
variables the for loop is now just the simple
C for loop.
11
12. March 2016 NoVa Python Meetup
$ ipython
In [1]: %load_ext Cython
In [2]: %%cython
...: def fib(n):
...: a = 0
...: b = 1
...: for i in range(n):
...: a, b = a + b, a
...: return a
...:
In [4]: %ls ~/.ipython/cython/
Users/
_cython_magic_65fad53c09eafb137d14870b4cf57507.c
_cython_magic_65fad53c09eafb137d14870b4cf57507.cpython-35m-darwin.so*
_cython_magic_65fad53c09eafb137d14870b4cf57507.pyx
In [5]: %whos
Variable Type Data/Info
--------------------------------------------------
fib builtin_function_or_method <built-in function fib>
12
How to Run Cython Code (IPython magic %%cython)
13. March 2016 NoVa Python Meetup
$ ipython
In [1]: import pyximport
In [2]: pyximport.install()
Out[2]: (None, <pyximport.pyximport.PyxImporter at 0x104dcba90>)
In [3]: import cyfib
In [4]: %whos
Variable Type Data/Info
-------------------------------
cyfib module <module 'cyfib' (/Users/a<...>b.cpython-35m-darwin.so)>
pyximport module <module 'pyximport' from <...>s/pyximport/__init__.py>
In [5]: %ls ~/.pyxbld/lib.macosx-10.10-x86_64-3.5/
cyfib.cpython-35m-darwin.so*
13
How to Run Cython Code (On import: pyximport)
14. March 2016 NoVa Python Meetup
setup.py file:
from distutils.core import setup
from Cython.Build import cythonize
setup(ext_modules=cythonize('cyfib.pyx'))
Build command:
$ python setup.py build_ext --inplace
14
How to Run Cython Code (Python build tools)
15. March 2016 NoVa Python Meetup
15
Performance Comparison
Version Runtime Speedup
Python 6.39 µs 1x
Compiled Python 4.1 µs 1.56x
Cython 167 ns 38.26x
%timeit fib(100)
16. March 2016 NoVa Python Meetup
● Most performance improvements for CPU-bound tasks
● Could somewhat help for memory-bound tasks
● Not appropriate for I/O- or network-bound tasks
● Value overflow possible when replacing Python data types with C data types
● Always first profile to locate and quantify execution bottlenecks!
16
When to use Cython?
17. March 2016 NoVa Python Meetup
Selected Cython Language Features
17
18. March 2016 NoVa Python Meetup
cdef int a = 0
cdef long b
cdef double c
cdef float **p = NULL
cdef list l
cdef tuple t
cdef object o
Variables without declared type in Cython code treated as standard Python variables.
18
Static Typing: cdef keyword
19. March 2016 NoVa Python Meetup
19
Declaration of structs, unions, enums
ctypedef struct xyz:
int x
float y
long z
ctypedef union u:
short a
double b, c
ctypedef enum H5Q_match_op_t:
H5Q_MATCH_EQUAL,
H5Q_MATCH_NOT_EQUAL,
H5Q_MATCH_LESS_THAN,
H5Q_MATCH_GREATER_THAN
20. March 2016 NoVa Python Meetup
Four ways:
cdef xyz v = xyz(1, 2.0, 3)
cdef xyz v = xyz(x=1, z=3, y=2.0)
cdef xyz v = {'z': 3, 'y': 2.0, 'x': 1}
cdef xyz v
v.x = 1
v.y = 2.0
v.z = 3
20
Assignment to structs
21. March 2016 NoVa Python Meetup
Pointer’s value at location 0 dereferences the pointer.
cdef int *p, a
a = 5
p = &a
print p[0] # prints: 5
21
C Pointers in Cython
22. March 2016 NoVa Python Meetup
● C’s char* and C++’s string types are automatically treated as the bytes type.
● Python string variables just work but the cython compiler will issue warning if
explicit decoding/encoding is needed.
● The bytes type is supported as is.
● Cython’s str type is treated as bytes in Python 2 and str in Python 3.
● Cython’s unicode type is unicode type in Python 2 and str type in Python 3.
● Implicit conversion between bytes and unicode/str types not allowed by default.
● Global compiler directives c_string_type and c_string_encoding control
implicit string conversion.
22
Strings in Cython
23. March 2016 NoVa Python Meetup
● Implementation files (.pyx) can be written in either syntax.
● The generated C/C++ source code is both Python 2 and 3 compatible.
● The default is Python 2 syntax.
● Can be specified with the -2 or -3 cython command line options.
● Imports from __future__ are supported.
23
Python 2 or 3
24. March 2016 NoVa Python Meetup
● Cython supports standard Python functions defined with the def keyword.
● cdef keyword defines a C-style function. Return value type can be specified.
cdef long long fib(int n):
pass
● cdef functions need wrapper def functions to be callable from Python.
● cpdef functions behave like cdef when called from Cython and like def when
called from Python. Only data types supported in both Python and C/C++ are
allowed, e.g. not void.
● inline keyword can be used in cdef and cpdef functions.
24
def, cdef, cpdef
25. March 2016 NoVa Python Meetup
● Exceptions generated in cdef and cpdef functions that don’t return a Python
object are not propagated automatically.
● except keyword declares an exception value.
cdef int foo(double x) except -1:
pass
● If an exception occurs in foo(), the returned value will be set to -1 which will
cause the exception to be propagated.
● Using except? (note the question mark) means that -1 is a legal return value from
the foo() function so the Cython-generated C/C++ code will include a call to
PyErr_Occurred() to check first if there was an exception.
● With except * calls to PyErr_Occurred() are always made.
25
Exception Handling
26. March 2016 NoVa Python Meetup
● Cython allows definition of classes that act as Python built-in types.
● Such extension type classes have C-level access to all methods and data.
cdef class Matrix:
cdef:
unsigned int nrows, ncols
double *_matrix
def __cinit__(self, nr, nc):
self.nrows = nr
self.ncols = nc
self._matrix = <double*>malloc(nr * nc * sizeof(double))
if self._matrix == NULL:
raise MemoryError()
def __dealloc__(self):
if self._matrix != NULL:
free(self._matrix)
26
Extension Types
Example code from: Cython, Kurt Smith, O’Reilly, 2015.