Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

c++ - How to measure the time that a piece of code takes to execute?

Suppose I want to measure the time that a certain piece of code takes. For that I would normally do something like this

clock_t startTime = clock();
//do stuff
//do stuff
//do stuff
//do stuff
float secsElapsed = (float)(clock() - startTime)/CLOCKS_PER_SEC;

What if the program is multithreaded and context switches occur within the part which I want to measure? How would I measure the time that my code takes to execute excluding time spent on other threads? Even if there are tools that do it, I would very much like to know how they're doing it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are different ways to measure how long code takes to execute.

If you are interested in the relative performance of certain functions, a profiler is the only way to go. Note that this will de-emphasise the impact of blocking I/O due to the computation overheads it induces.

If you want the clock-based time of certain functions, there are loads of options.

Personally I would say gettimeofday is sufficient.

If you want to get precise, use RDTSC

If you want to get really precise, you'll want something like this

t1 = rdtsc();
t2 = rdtsc();
my_code();
t3 = rdtsc();
my_code_time = (t3-t2) - (t2-t1)

You will need to repeat this block to account for thread scheduling discrepencies, and also pay attention to cacheing effects.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...