从C#调用C ++ / CLI会随着时间的推移而变慢

时间:2014-07-14 09:00:10

标签: c# c++-cli interop

我正在为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*投射可能是不必要的,但我看不出它们会变得越来越慢。

正常运行时的输出

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

导致这种放缓行为的原因是什么?

1 个答案:

答案 0 :(得分:0)

我终于找到了这个问题。在 Release 模式下编译libtorrent时,一切都按预期运行。我想在运行debug时会发生一些沉重的断言。