问题描述
作为主题,我编写了一个cpp文件并使用ndk构建它:
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <vector>
struct timeval start;
struct timeval finish;
unsigned long spend;
std::vector<char> test_v1;
std::vector<char> test_v2;
void* test(void* data) {
int count = 0;
for(int i = 0; i < 512; i++)
{
test_v2.push_back(1);
}
printf("START\n");
while(1){
for(int j = 0; j < 5; j++)
{
for(int i = 0; i < 3; i++)
{
test_v1.insert(test_v1.end(),test_v2.begin(),test_v2.end());
}
for(int i = 0; i < test_v1.size(); i++)
{
test_v1.at(i) = 0;
}
test_v1.clear();
}
//pthread_mutex_lock(&_p_mutex);
gettimeofday(&start,NULL);
usleep(16000);
gettimeofday(&finish,NULL);
spend = 1000000 * (finish.tv_sec-start.tv_sec)+ finish.tv_usec-start.tv_usec;
if(spend > 30000){
printf("[ERROR] : over 30ms,spend = %lu\n",spend);
}
count++;
if(count >= 180){
printf("Keep Alive,spend %lu\n",spend);
count = 0;
}
for(int j = 0; j < 5; j++)
{
for(int i = 0; i < 3; i++)
{
test_v1.insert(test_v1.end(),test_v2.end());
}
for(int i = 0; i < test_v1.size(); i++)
{
test_v1.at(i) = 0;
}
test_v1.clear();
}
}
return 0;
}
int main(void){
printf("No thread Test\n");
int rtn = 0;
test(NULL);
return rtn;
}
执行结果: pic
没有其他应用程序正在执行,并且系统加载非常轻。
最奇怪的是,在不同的开机->测试->关机周期中,这种情况可能不会发生,并且当发生周期时,无论我重新启动测试有多少次,这种情况总是会发生关闭Android设备的电源。
为什么睡眠时间会受到许多矢量操作的影响?
系统规格
Android版本:7.0
设备根:是
Android NDK版本:r11c
使用Cygwin和ADB Shell执行。
Android.mk:
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := threadtest
LOCAL_SRC_FILES := threadtest.cpp
include $(BUILD_EXECUTABLE)
Application.mk:
NDK_TOOLCHAIN_VERSION := 4.9
APP_OPTIM := debug
APP_STL := gnustl_shared
APP_CPPFLAGS := -std=gnu++14 -frtti -fexceptions
APP_CFLAGS := -fopenmp -ggdb
APP_LDFLAGS := -llog -fopenmp
APP_BUILD_SCRIPT := Android.mk
APP_PIE := true
编辑:
我用直接内存分配和设置代替了向量操作。
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <vector>
struct timeval start;
struct timeval finish;
unsigned long spend;
void* test(void* data) {
int count = 0;
printf("START\n");
while(1){
for(int j = 0; j < 10; j++)
{
char* p = (char*)malloc(sizeof(char) * 1000);
for(int i = 0; i < (sizeof(char) * 1000); i++)
{
p[i] = 2;
}
for(int i = 0; i < (sizeof(char) * 1000); i++)
{
p[i] = 1;
}
for(int i = 0; i < (sizeof(char) * 1000); i++)
{
p[i] = 0;
}
free(p);
}
gettimeofday(&start,spend);
}
count++;
if(count >= 180){
printf("keep alive,spend);
count = 0;
}
for(int j = 0; j < 10; j++)
{
char* p = (char*)malloc(sizeof(char) * 1000);
for(int i = 0; i < (sizeof(char) * 1000); i++)
{
p[i] = 2;
}
for(int i = 0; i < (sizeof(char) * 1000); i++)
{
p[i] = 1;
}
for(int i = 0; i < (sizeof(char) * 1000); i++)
{
p[i] = 0;
}
free(p);
}
}
return 0;
}
int main(void){
printf("No thread Test\n");
int rtn = 0;
test(NULL);
return rtn;
}
结果是相同的。
似乎很多内存操作都会导致此问题,但是为什么呢?所有这些都应该在第一个gettimeofday之前完成吗?
解决方法
延迟不是由于使用向量引起的,而是因为您的代码未优化。向量遍历有时间开销。在您的代码中,您通过在嵌套循环内调用而过于频繁地遍历向量。 push_back操作将比插入操作执行得更快。对于频繁插入的内容,列表会更好。