我正在使用 timeit 对项目的一些代码进行基准测试(使用免费的 replit,因此需要 1024MB 内存):
\ncode = \'{"type":"body","layers":[\'\n\nfor x, row in enumerate(pixels):\n for y, pixel in enumerate(row):\n if pixel != (0, 0, 0, 0):\n code += f\'\'\'{{"offsetX":{-start + x * gap},"offsetY":{start - y * gap},"rot":45,"size":{size},"sides":4,"outerSides":0,"outerSize":0,"team":"{\'#%02x%02x%02x\' % (pixel[:3])}","hideBorder":1}},\'\'\'\n \ncode += \'],"sides":1,"name":"Image"}}\nRun Code Online (Sandbox Code Playgroud)\n该循环针对给定图像内的每个像素运行(当然效率不高,但我还没有实现任何减少循环时间的方法),因此我可以在循环中获得的任何优化都是值得的。
\n我记得只要你组合 3 个以上的字符串\xe2\x80\x94,f 字符串就比字符串连接更快,如图所示,我组合了超过3个字符串\xe2\x80\x94,所以我决定将循环内的 += 替换为 f 字符串并查看改进。
\ncode = \'{"type":"body","layers":[\'\n\nfor x, row in enumerate(pixels):\n for y, pixel in enumerate(row):\n if pixel != (0, 0, 0, 0):\n code = f\'\'\'{code}{{"offsetX":{-start + x …Run Code Online (Sandbox Code Playgroud)