在尝试为另一个SO问题写一个答案的时候发生了一件非常奇怪的事情.
我基本上想出了一个内置gcd并说 it maybe slower because of recursion
gcd = lambda a,b : a if not b else gcd(b, a % b)
这是一个简单的测试:
assert gcd(10, 3) == 1 and gcd(21, 7) == 7 and gcd(100, 1000) == 100
Run Code Online (Sandbox Code Playgroud)
这里有一些基准:
timeit.Timer('gcd(2**2048, 2**2048+123)', setup = 'from fractions import gcd').repeat(3, 100)
# [0.0022919178009033203, 0.0016410350799560547, 0.0016489028930664062]
timeit.Timer('gcd(2**2048, 2**2048+123)', setup = 'gcd = lambda a,b : a if not b else gcd(b, a % b)').repeat(3, 100)
# [0.0020480155944824219, 0.0016460418701171875, 0.0014090538024902344]
Run Code Online (Sandbox Code Playgroud)
那很有意思,我预计会慢很多,但时间相当接近,?也许导入模块是问题...
>>> setup = ''' …Run Code Online (Sandbox Code Playgroud) 我已经广泛使用了结构,并且我已经看到了一些有趣的东西,特别是*value代替value->first_value值是指向struct的指针,first_value是第一个成员,是否*value安全?
另请注意,由于对齐,无法保证大小,基于结构/寄存器大小的alginment值是什么?
我们对齐数据/代码以便更快地执行,我们可以告诉编译器不要这样做吗?那么也许我们可以保证结构的某些东西,比如它们的大小?
当对结构成员进行指针运算以便定位成员偏移时,我认为-如果对大端+进行小端,或者仅仅依赖于编译器吗?
malloc(0)真正分配了什么?
以下代码用于教育/发现目的,并不意味着具有生产质量.
#include <stdlib.h>
#include <stdio.h>
int main()
{
printf("sizeof(struct {}) == %lu;\n", sizeof(struct {}));
printf("sizeof(struct {int a}) == %lu;\n", sizeof(struct {int a;}));
printf("sizeof(struct {int a; double b;}) == %lu;\n", sizeof(struct {int a; double b;}));
printf("sizeof(struct {char c; double a; double b;}) == %lu;\n", sizeof(struct {char c; double a; double b;}));
printf("malloc(0)) returns %p\n", malloc(0));
printf("malloc(sizeof(struct {})) returns %p\n", malloc(sizeof(struct {})));
struct {int a; …Run Code Online (Sandbox Code Playgroud)