在Julia中,为什么@printf是宏而不是函数? [英] In Julia, why is @printf a macro instead of a function?

查看:139
本文介绍了在Julia中,为什么@printf是宏而不是函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Julia中,用于打印格式化字符串的语法如下:

In Julia, the syntax to print a formatted string is as follows:

@printf("Hello %d\n", 5)

为什么@printf是宏而不是函数?这样是否可以接受不同数量的参数?

Why is @printf a macro instead of a function? Is it so that it can accept a varying number of arguments?

推荐答案

对于普通的Julia函数,采用可变数量的参数不是问题[

Taking a variable number of arguments is not a problem for normal Julia functions [1]. @printf is a macro so that it can parse and interpret the format string at compile time and generate custom code for that specific format string. People may not realize that C's printf function re-parses and re-interprets the format string each time you call printf. The fact that it's as fast as it is represents a minor miracle of insane pointer programming. Seriously, just look at your nearest libc's printf implementation. It's completely nuts.

Julia使用另一种方法:@printf是一个宏,它将格式字符串转换为特定于该格式规范的有效代码.如果您考虑一下,printf样式的格式字符串实际上只是表达一个函数的一种方式,该函数采用固定数量和类型的参数并以特定方式打印它们.请注意,我说过 format字符串是一个函数,而不是printf本身,后者在概念上是一个函数生成器,它将格式转换为格式器.由于C是C中唯一合理的选择,因此所有这些都挤在了C的运行时函数中,这有点不匹配.事实上,因此,直到最近,射击自己还是很容易的通过将错误的数字或类型的参数传递给C的printf来解决问题.这只是现在更好,因为编译器已经过特殊处理,可以理解printf格式的语义.

Julia uses a different approach: @printf is a macro which translates format strings into efficient code specific to that format specification. If you think about it, a printf-style format string is really just a way to express a function that takes a fixed number and type of arguments and prints them in a particular way. Note that I said that the format string is a function, not printf itself, which is conceptually a function generator, turning formats into formatters. The fact that this is all crammed into a run-time function in C is a bit of a mismatch due to that being the only reasonable option in C. In fact, because of this, until very recently, it was rather easy to shoot yourself in the foot by passing the wrong number or type of arguments to C's printf. This is only better now because compilers have been special-cased to understand the semantics of printf formats.

从理论上讲,Julia的@printf可以比C更快,因为它生成了自定义代码,但是实际上,我有足够的时间来匹配C,更不用说殴打它了.但是我认为这是由于我们的I/O系统的当前设计以及我的使用方式所致,而不是固有的局限性. I/O内容需要进行大修,而当发生这种情况时,实际上我们可以利用@printf是宏的事实在格式打印方面胜过C.

In theory, Julia's @printf can be made faster than C since it generate's custom code, but in practice, I had a hard enough time matching C, let alone beating it. But I think that's due to the current design of our I/O system and how I'm using it, not an inherent limitation. The I/O stuff is due for an overhaul though, and when that happens, we might actually be able to beat C at formatted printing by leveraging the fact that @printf is a macro.

这篇关于在Julia中,为什么@printf是宏而不是函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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