Can I use SPI communication and serial communication at the same time?

I use Arduino MEGA to communicate with PC and SPI device.(PC ⇔ Arduino ⇔ SPI device).

I use HardwareSerial so I hope that serial and SPI can communicate at the same time.
For example, Serial communication takes 5ms and SPI communication takes 9ms,I hope the whole time is only 9ms.But it takes 14ms.

Here is my code.

#include <SPI.h>
#define BUFF_SIZE 1024
byte buff[BUFF_SIZE] = {0};
byte test_buff[16];


SPISettings mySPISettings = SPISettings(1000000, LSBFIRST, SPI_MODE3);

unsigned long start_time = 0;
unsigned long end_time = 0;
void setup() {

  SPI.begin();
  SPI.beginTransaction(mySPISettings);
  
  digitalWrite(SS, HIGH);
   
  
  Serial.begin(115200);
  
  while(!Serial){
  
    ;
  }
  
}

void loop() {
  start_time = micros();
  
  Serial.readBytes(test_buff, 16);
  
  digitalWrite(SS, LOW);      
  SPI.transfer(buff, 1024);
  digitalWrite(SS, HIGH);

  end_time = micros();
  
  Serial.println(end_time - start_time);
}

Serial.readbytes() is a blocking function.

Have a look at the examples in Serial Input Basics - simple reliable non-blocking ways to receive data.

An Arduino can only do one thing at a time. You can create the impression of multi-tasking by breaking long-running tasks into smaller chunks and interleaving them.

The actual receipt of the Serial data into the Serial Input Buffer should happen in the background as it is interrupt driven. Your code does not need to do anything until it actually wants to take the data from the Buffer. Consequently I'm not convinced that your timing test is realistic.

It will be much easier to give useful advice if you describe your project and explain the need for "same-time" communication.

...R

The Uno process one instruction at a time. No, the Arduino cannot do 2 things at the same time but you can use SPI and serial in the same sketch.

For example, Serial communication takes 5ms and SPI communication takes 9ms,I hope the whole time is only 9ms.But it takes 14ms.

Sure, that's because your SPI code depends on the result of the serial code. Theoretically the UNO is able to do some SPI transfers while receiving or sending serial data (given you use the hardware for that). But if you prevent that by explicit coding it's your fault.