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

标签 c++ performance qt dllimport qlibrary

我正在使用 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/

相关文章:

c++ - 赋值运算符(+= 和 =)之间的区别

c++ - 理解值绑定(bind)器

c++ - VS2008 链接到错误的 boost 库

c++ - 使用鼠标拖动时使用 atan2 旋转图像

qt - 无法在 QVBoxLayout 中调整小部件的大小

qt - foreach在QPair列表上不起作用

wpf - 并排运行 WPF/Win32 应用程序的性能问题?

mysql - 与 wp_postmeta 连接的 wp_posts 内部的 Wordpress 慢速查询

java - 哪种功能组合方式最专业

c++ - 如何访问子类中的小部件?