适用于Python的C预处理器宏 [英] C Preprocessor Macro equivalent for Python

查看:90
本文介绍了适用于Python的C预处理器宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常在C语言中定义宏(而不仅仅是常量)

I use to define macros (not just constants) in C like

#define loop(i,a,b) for(i=a; i<b; ++i)
#define long_f(a,b,c) (a*0.123 + a*b*5.6 - 0.235*c + 7.23*c - 5*a*a + 1.5)

是否有一种方法可以在python中使用预处理而不是函数?

Is there a way of doing this in python using a preprocess instead of a function?

*通过预处理的意思是在运行代码之前,它代替了定义的出现(实际上不是整个代码,而是其余代码,因为我猜这是代码的一部分,我想它将在运行时替换所有内容.

*By preprocess I mean something that replaces the occurrences of the definition before running the code (actually not the whole code but the rest of the code, because since it's part of the code, I guess it will replace everything during runtime).

如果有,值得吗?运行时间会不会有明显的不同?

If there is, worth it? Will there be a significant difference in run time?

推荐答案

好吧,如果您要执行一些可以预先执行的非常困难的计算,那么也许这是有道理的:通常,用户会更满意使用快速程序而不是慢速程序.

Well, if you're going to perform some really hard calculations that could be performed in advance, then, perhaps, this makes sense: usually users are more happy with fast programs rather than slow ones.

但是,恐怕在原始性能"(即算术计算速度)方面,python不是一个不错的选择.至少如果我们谈论称为CPython的标准python实现.

But, I'm afraid python isn't a good choice when it comes to 'raw performance', that is, speed of arithmetic calculations. At least if we talk about the standard python implementation, called CPython.

或者,您可以检查其他变体:

Alternatively, you could check other variants:

  • PyPy .这是纯Python中的另一种python实现.借助JIT编译器,它可以提供更好的性能,但需要更多的内存.
  • Cython .这是对Python的扩展,它使人们可以[方便地]为代码的关键部分创建可编译的片段.
  • 使用您喜欢的任何外部预处理器. M4
  • PyPy. This is an alternative python implementation, in pure Python. Thanks to a JIT compiler it gives better performance but requires a lot more memory.
  • Cython. This is an extension to Python, which allows one to [conveniently] create compileable snippets for perfomance critical parts of the code.
  • Use a whatever external pre-processor you like. M4 and FilePP are what come to my mind first, but there're plenty of them.

这篇关于适用于Python的C预处理器宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆