随着时间的推移,从c#调用c++ /CLI变得越来越慢

本文关键字:CLI c++ 越来越 调用 时间 | 更新日期: 2023-09-27 18:12:51

我正在为一个c++库编写一个c++/CLI包装库。c++/CLI不是我喜欢的语言,但经过几次尝试和失败后,我已经成功地从c#中生成了一个可以使用的托管库。

问题是,随着时间的推移,调用函数会逐渐变慢。一开始大约需要3-4ms(用秒表测量),然后逐渐增加到4000ms甚至更高。

这些是相关的代码片段。请注意,我删除了命名空间的内容,并合并了.cpp/.h文件,以使其更易于阅读。

Program.cs

using (var session = new Session())
{
    Stopwatch stopWatch;
    var handle = session.Add(addParams);
    while (true)
    {
        stopWatch.StartNew();
        handle.GetStatus(); // This call is gradually getting slower.
        stopWatch.Stop();
        Console.WriteLine("{0}ms to get status.", stopWatch.ElapsedMilliseconds);
        Thread.Sleep(1000);
    }
}

Session.h

public ref class Session
{
private:
    void* _pointer;
    property libtorrent::session* Pointer
    {
        inline libtorrent::session* get()
        {
            return (libtorrent::session*)this->_pointer;
        }
    }
public:
    Session()
    {
        this->_pointer = new libtorrent::session();
    }
    TorrentHandle^ Add(AddTorrentParams ^addTorrentParams)
    {
        auto handle = this->Pointer->add_torrent(*addTorrentParams->Pointer);
        return gcnew TorrentHandle(handle);
    }
}

TorrentHandle.h

public ref class TorrentHandle
{
private:
    void* _pointer;
    property libtorrent::torrent_handle* Pointer
    {
        inline libtorrent::torrent_handle* get()
        {
            return (libtorrent::torrent_handle*)this->_pointer;
        }
    }
internal:
    TorrentHandle(libtorrent::torrent_handle const &handle)
    {
        this->_pointer = (void*) new libtorrent::torrent_handle(handle);
    }
public:
    TorrentStatus^ GetStatus()
    {
        return gcnew TorrentStatus(this->Pointer->status());
    }
}

TorrentStatus.h

public ref class TorrentStatus
{
private:
    void* _pointer;
    property libtorrent::torrent_status* Pointer
    {
        inline libtorrent::torrent_status* get()
        {
            return (libtorrent::torrent_status*)this->_pointer;
        }
    }
public:
    TorrentStatus(libtorrent::torrent_status &status)
    {
        this->_pointer = (void*)new libtorrent::torrent_status(status);
    }
}

我知道一些void*的cast可能是不必要的,但我不明白为什么这些会变得越来越慢。

正常运行的输出

0ms to get status
0ms to get status
0ms to get status
1ms to get status
94ms to get status
18ms to get status
15ms to get status
68ms to get status
114ms to get status
112ms to get status
123ms to get status
130ms to get status
220ms to get status
210ms to get status
371ms to get status
277ms to get status
1152ms to get status
1081ms to get status
1384ms to get status
1424ms to get status
1387ms to get status
1520ms to get status
1471ms to get status
605ms to get status
1201ms to get status
1038ms to get status
1672ms to get status

是什么导致了这种减速行为?

随着时间的推移,从c#调用c++ /CLI变得越来越慢

我终于找到问题了。当在Release模式下编译libtorrent时,一切都正常运行。