测量将参数传递给函数所需的时间(Measure time it takes to pass the parameters to the function)

编程入门 行业动态 更新时间:2024-10-25 23:33:12
测量将参数传递给函数所需的时间(Measure time it takes to pass the parameters to the function)

有没有办法通过传递参数来衡量函数花费了多少时间? 我的想法是测量函数的主体和整个函数本身。 这是正确的方法吗? 下面的伪代码:

int main(){ int start = time.now(); // passing by value int timeOfFunc = foo(vector<my_object> huge_vector, vector<my_object2> huge_vector2); int end = time.now(); int timeSpentPassingArgs = (end - start) - timeOfFunc; // getting time it takes to pass the argument? } int foo(vector<my_object> huge_vector, vector<my_object2> huge_vector2) { int start = time.now(); // body of the foo function int end = time.now(); return (end - start); }

Is there a way to measure how much time the function has spent by passing the parameters? My thought is to measure the body of the function and the whole function itself. Is that the right approach? Pseudo code below:

int main(){ int start = time.now(); // passing by value int timeOfFunc = foo(vector<my_object> huge_vector, vector<my_object2> huge_vector2); int end = time.now(); int timeSpentPassingArgs = (end - start) - timeOfFunc; // getting time it takes to pass the argument? } int foo(vector<my_object> huge_vector, vector<my_object2> huge_vector2) { int start = time.now(); // body of the foo function int end = time.now(); return (end - start); }

最满意答案

我看不出你的方法有什么问题,除了你的时间将包括在函数中调用time.now()两次所花费的时间。 与复制的成本相比,这应该是非常小的。

您可以尝试的另一个选项如下(使用伪代码):

function(parameters) { return time.now(); } // calling code time start = time.now(); time end = function(paramters); time total_time = end - start;

这应该告诉你确切地调用函数和复制参数需要多长时间。 我不确定编译器是否允许/可以优化掉未使用的参数副本,但如果确实如此,则应该只获得零。

I can't see anything wrong with your approach except that you timings will include the time it takes to call time.now() twice in the function. That should be pretty minor though compared to the cost of the copying.

Another option you can tries follows like (using pseudo code):

function(parameters) { return time.now(); } // calling code time start = time.now(); time end = function(paramters); time total_time = end - start;

And that should tell you exactly how long it takes to just call the function and copy the parameters. I'm not sure if the compiler is allowed to/can optimized out an unused copy of the parameters but if it does you should just get a zero.

更多推荐

本文发布于:2023-08-02 15:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1378622.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所需   函数   测量   参数   时间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!