Love Lua ffi具有中等大小的功能更快,但大小功能较慢
我一直在使用Love 2D了解Luajit和Lua FFI库。为了测试FFI是否真的更快,我编码了一个函数以计数一个范围内的所有素数。
(代码可能不准确,我只是想要两种语言都可以得到相同答案的硬数学问题)
// test.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double numberBuffer;
double getPrimes(double n) {
double count = 0;
for (double i = 1; i <= n; i++) {
double cap = pow(i, 0.5);
for (double num = 2; num <= cap; num++) {
if (fmod(i, num) == 0) {
count++;
break;
}
}
}
numberBuffer = count;
return numberBuffer;
}
-- main.lua
local ffi = require("ffi")
function loadFFI(name)
local dir = love.filesystem.getRealDirectory("bin/" .. name .. ".so")
return ffi.load(dir .. "bin/" .. name .. ".so")
end
local test = loadFFI("test")
ffi.cdef[[
double getPrimes(double n);
]]
local function getPrimes(n)
local count = 0
for i = 1,n do
for num = 2, i^(0.5) do
if (i % num) == 0 then
count = (count + 1)
break
end
end
end
return count
end
function love.load()
local one, two = 0, 0
local n = 60000
local time = love.timer.getTime()
local c = test.getPrimes(n)
one = (love.timer.getTime() - time)
time = love.timer.getTime()
local lua = getPrimes(n)
two = (love.timer.getTime() - time)
print("n = " .. tostring(n))
print("C", c, (tostring(one * 1000) .. " miliseconds"))
print("Lua", lua, (tostring(two * 1000) .. " miliseconds"))
end
起初,结果是我预期的。我认为,卢阿(Lua)的速度很小,因为开销。使用稍大的集合,C变得更快。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
感谢Ikegami在评论中回答。
将双打更改为INT,并用%操作员替换FMOD解决了问题。
Thanks to Ikegami for answering in comments.
Changing the doubles to ints, and replacing fmod with the % operator solved the issue.
我想知道您不使用
love.graphics.print()
inlove.draw()
...I am wondering about that you not using
love.graphics.print()
inlove.draw()
...