c – CPP中速度性能的测试功能
作者:互联网
我创建了一个简单的函数来将任何小写字母a-z转换为大写,问题可能不是问题,但每个测试都返回0.如果我添加系统(“暂停”),我可以看到一个新值,表示暂停的长度.
有没有更准确的方法来测试速度,或者这实际上是否正确?我想将它与其他函数进行比较,看它是否比标准函数更快地转换.
char* ToUppercase(char* Input)
{
int Len = Length(Input);
for (int i = 0; i < Len; i++)
{
short keycode = static_cast<short>(Input[i]);
if (keycode >= 97 && keycode <= 122)
Input[i] -= 32;
}
return Input;
}
我用来测试的当前计时器是(由其他人创建)
template<typename TimeT = std::chrono::milliseconds>
struct measure
{
template<typename F, typename ...Args>
static typename TimeT::rep execution(F func, Args&&... args)
{
auto start = std::chrono::system_clock::now();
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast< TimeT>
(std::chrono::system_clock::now() - start);
return duration.count();
}
};
打电话我用:
void Debug()
{
char Buffer[10000] = "aaaa /..../ aaaa";
MyStringControl::ToUppercase(Buffer);
}
int main()
{
std::cout << measure<std::chrono::nanoseconds>::execution(Debug);
}
解决方法:
你看过std :: chrono :: high_resolution_clock吗?
这是一个例子:
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>
template<typename TimeT = std::chrono::milliseconds>
struct measure
{
template<typename F, typename ...Args>
static typename TimeT::rep execution(F func, Args&&... args)
{
auto start = std::chrono::high_resolution_clock::now();
func(std::forward<Args>(args)...);
auto duration = std::chrono::duration_cast< TimeT>
(std::chrono::high_resolution_clock::now() - start);
return duration.count();
}
};
int total = 0;
void test()
{
int foo = 0;
for (int i=0; i<1000; ++i) ++foo;
total += foo;
}
int main ()
{
using namespace std::chrono;
for (int i = 0; i < 30; ++i)
{
total = 0;
auto t = measure<std::chrono::nanoseconds>::execution(test);
std::cout << "Calculated total = " << total << " in " << t << " ns." << std::endl;
}
return 0;
}
这使:
Calculated total = 1000 in 64 ns.
Calculated total = 1000 in 21 ns.
Calculated total = 1000 in 22 ns.
Calculated total = 1000 in 21 ns.
Calculated total = 1000 in 14 ns.
Calculated total = 1000 in 15 ns.
Calculated total = 1000 in 13 ns.
Calculated total = 1000 in 14 ns.
Calculated total = 1000 in 13 ns.
Calculated total = 1000 in 14 ns.
Calculated total = 1000 in 13 ns.
Calculated total = 1000 in 21 ns.
Calculated total = 1000 in 14 ns.
Calculated total = 1000 in 15 ns.
Calculated total = 1000 in 14 ns.
Calculated total = 1000 in 15 ns.
Calculated total = 1000 in 22 ns.
Calculated total = 1000 in 21 ns.
Calculated total = 1000 in 20 ns.
Calculated total = 1000 in 14 ns.
Calculated total = 1000 in 14 ns.
Calculated total = 1000 in 14 ns.
Calculated total = 1000 in 20 ns.
Calculated total = 1000 in 20 ns.
Calculated total = 1000 in 21 ns.
Calculated total = 1000 in 20 ns.
Calculated total = 1000 in 15 ns.
Calculated total = 1000 in 15 ns.
Calculated total = 1000 in 15 ns.
Calculated total = 1000 in 14 ns.
标签:c,c11,performance-testing 来源: https://codeday.me/bug/20190824/1710716.html