gpt4 book ai didi

c++ - QLibrary 函数在第一次调用时运行缓慢

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:40:26 26 4
gpt4 key购买 nike

我正在使用 QLibrary 从一个 .dll 文件加载函数。我成功加载它,成功解析功能。但是当我第一次使用那个 .dll 中的某些函数时,这个函数运行起来非常慢(即使它是一个非常简单的函数)。下次我再次使用它时 - 速度很好(立即,应该如此)。

这种行为的原因是什么?我怀疑某处有缓存。

编辑 1:代码:

typedef int(*my_type)(char *t_id);
QLibrary my_lib("Path_to_lib.dll");
my_lib.load();
if(my_lib.isLoaded){
my_type func = (my_type)my_lib.resolve("_func_from_dll");
if(func){
char buf[50] = {0};
char buf2[50] = {0};
//Next line works slow
qint32 resultSlow = func(buf);
//Next line works fast
qint32 resultFast = func(buf2);
}
}

最佳答案

我不会责怪 QLibrary:func 只是在第一次调用时需要很长时间。我敢打赌,如果您使用特定于平台的代码解析其地址,您将获得相同的结果,例如Linux 上的 dlopendlsymQLibrary 除了包装平台 API 之外并没有做太多事情。没有任何特定的东西会使第一次调用变慢。

在可能是通用类的构造函数中执行文件 I/O 有一些代码味道:类的用户是否知道构造函数可能会阻塞磁盘 I/O,因此理想情况下不应从 GUI 线程调用? Qt 使异步执行此任务变得相当容易,所以我至少会尝试以这种方式表现得很好:

class MyClass {
QLibrary m_lib;
enum { my_func = 0, other_func = 1 };
QFuture<QVector<FunctionPointer>> m_functions;
my_type my_func() {
static my_type value;
if (Q_UNLIKELY(!value) && m_functions.size() > my_func)
value = reinterpret_cast<my_type>(m_functions.result().at(my_func));
return value;
}
public:
MyClass() {
m_lib.setFileName("Path_to_lib.dll");
m_functions = QtConcurrent::run{
m_lib.load();
if (m_lib.isLoaded()) {
QVector<QFunctionPointer> funs;
funs.push_back(m_lib.resolve("_func_from_dll"));
funs.push_back(m_lib.resolve("_func2_from_dll"));
return funs;
}
return QVector<QFunctionPointer>();
}
}
void use() {
if (my_func()) {
char buf1[50] = {0}, buf2[50] = {0};
QElapsedTimer timer;
timer.start();
auto result1 = my_func()(buf1);
qDebug() << "first call took" << timer.restart() << "ms";
auto result2 = my_func()(buf2);
qDebug() << "second call took" << timer.elapsed() << "ms";
}
}
};

关于c++ - QLibrary 函数在第一次调用时运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com